如何在改造调用中发送 byte[] 数组。我只需要发送 byte[]。当我尝试发送 retrofit 电话时出现此异常。
retrofit.RetrofitError: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
我可以通过什么样的方式进行改造。
我只是将字节数组作为封装在对象类中的 ByteMessage 传递。
public class ByteMessage {
private byte[] byteArray;
byte[] getByteArray() {
return byteArray;
}
setByteArray(byte[] bytes){
byteArray = bytes;
}
}
@POST("/send")
sendBytes(ByteMesssage msg);
服务器端:
sendBytes(ByteMessage msg) {
byte[] byteArray = msg.getByte();
...doSomething...
}
我无法在堆栈溢出中找到资源,也无法通过谷歌搜索通过改造调用传递字节数组的正确解决方案。
谁能帮忙解决这个问题。
谢谢 迪仁
最佳答案
为此,您可以使用 TypedByteArray
您的 Retrofit 服务将如下所示:
@POST("/send")
void upload(@Body TypedInput bytes, Callback<String> cb);
您的客户端代码:
byte[] byteArray = ...
TypedInput typedBytes = new TypedByteArray("application/octet-stream", byteArray);
remoteService.upload(typedBytes, new Callback<String>() {
@Override
public void success(String s, Response response) {
//Success Handling
}
@Override
public void failure(RetrofitError retrofitError) {
//Error Handling
}
});
"application/octet-stream"- 而不是这个 MIME-TYPE,您可能想使用您的数据格式类型。您可以在此处找到详细信息: http://www.freeformatter.com/mime-types-list.html
和 Spring MVC Controller (如果你需要的话):
@RequestMapping(value = "/send", method = RequestMethod.POST)
public ResponseEntity<String> receive(@RequestBody byte[] data) {
//handle data
return new ResponseEntity<>(HttpStatus.CREATED);
}
关于java - 如何在改造中发送 byte[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325723/