Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ajax to send a Proto-buf message to a Java server

Using https://github.com/dcodeIO/ProtoBuf.js/ I encoded a message I want to send to a java server to a ByteBuffer called batch:

batch:
  ByteBuffer {array: ArrayBuffer, view: DataView, offset: 0, markedOffset: -1, length: 139…}
    array: ArrayBuffer
    length: 139
    littleEndian: false
    markedOffset: -1
    offset: 0
    view: DataView
    __proto__: Object

Now I want to send this with jquery's Ajax:

  $.ajax({
    url: myUrl,
    type: 'POST',
    data : batch,
    contentType: 'application/protobuf',
    accept: 'application/json'
  })

But I can't seem to do this. The above code gives me the jquery exception:

Uncaught TypeError: Cannot set property 'littleEndian' of undefined myScript.js:1353
ByteBuffer.LE bunk.js:1353
jQuery.param.add jquery.js:7203
buildParams jquery.js:7261
jQuery.param jquery.js:7223
jQuery.extend.ajax

If I get an array buffer from batch (batch.toArrayBuffer()) the Java server gets nothing from

ByteStreams.toByteArray(req.getInputStream());

How should I encode the ByteBuffer to send like this? And how should I decode it into a java byte array?

like image 902
Jason S Avatar asked Jun 19 '14 14:06

Jason S


1 Answers

Not sure if you found a solution but Google Protocol Buffers now come with a javascript compiler.

Once you have built your object to send with the proto builder, You can send data using jQuery using the following:

    $.ajax({
        type: "PUT",
        url: "http://localhost:8088/user",
        data: user.serializeBinary(),
        success: function () {
            $("#message").text("User with key " + user.getApikey() + " saved");
        },
        contentType: "application/x-protobuf",
        processData: false
    });

ProcessData: false is necessary to avoid jQuery serialising the data in the background.

like image 132
Tom Chamberlain Avatar answered Oct 16 '22 06:10

Tom Chamberlain