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

Using https://github.com/dcodeIO/ProtoBuf.js/ I encoded the message that I want to send to the Java server in ByteBuffer, called the package:

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 using jquery Ajax:

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

But I can’t do it. The above code gives me a 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 a package (batch.toArrayBuffer ()), the Java server does not receive anything from

 ByteStreams.toByteArray(req.getInputStream()); 

How do I encode a ByteBuffer to send as follows? And how do I decode it into a java byte array?

+6
source share
2 answers

From the jQuery documentation on ajax ( http://api.jquery.com/jquery.ajax/ ):

Note. The W3C XMLHttpRequest specification requires encoding to always be UTF-8; specifying a different encoding will not force the browser to change the encoding.

You are probably trying to send raw binary bytes from your protobuffer, which is incompatible with UTF-8.

I am not familiar with ProtoBuf.js, but from a little digging on the Internet it looks like the toBase64 () method is used as base64 for encoding protobuf. Try using this method to get the data to send, and then decode from base64 on the server.

0
source

Not sure if you found a solution, but now there is a javascript compiler in the buffers of the Google protocol.

Once you have built your object to be sent using 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 by serializing data in the background.

0
source

Source: https://habr.com/ru/post/971061/


All Articles