Java 如何在json post请求中发送字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24568735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to send byte array in json post request?
提问by Sajeetharan
I have a wcf service which accepts byte[] serialData
, now am developing a java client which needs to consume the same method.
我有一个接受的 wcf 服务 byte[] serialData
,现在正在开发一个需要使用相同方法的 java 客户端。
When i sent bytearray to the service as a json post request , it is getting an exception as java.io.IOException: Server returned HTTP response code: 400
当我将 bytearray 作为 json post 请求发送到服务时,它出现异常 java.io.IOException: Server returned HTTP response code: 400
Here is my code:
这是我的代码:
wcf method:
wcf方法:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "saveSerialNumbers", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
Dictionary<string, object> saveSerialNumbers(byte[] serialData);
Java Client:
Java客户端:
for (int i = 1; i < 100; i++) {
sb.append(String.valueOf(gen()));
}
byte[] bytesEncoded = Base64.encodeBase64(sb.toString().getBytes());
String json = "{\"serialDataByte\":\""+sb.toString()+"\"}";
This is my postrequest method:
这是我的 postrequest 方法:
public String getResultPOST(String jsonObject,String uri,String method) throws Exception{
try {
URL url = new URL(uri+method);
System.out.println(url.toString());
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out;
try {
out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject);
out.close();
} catch (Exception e) {
/
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = "";
StringBuilder builder = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = in.readLine()) != null) {
builder.append(line);
}
in.close();
return builder.toString();
} catch (Exception e) {
throw e;
//here is the exception
}
}
Here is my method call:
这是我的方法调用:
String json = "{\"serialData\":\""+ new String(bytesEncoded) +"\",\"guProductID\":\""+guProductID+"\",\"guStoreID\":\""+guStoreID+"\",\"securityToken\":\""+SecurityToken+"\"}";
String serialContract = serialClient.getResultPOST(json, "http://localhost:3361/EcoService.svc/Json/", "saveSerialNumbers");
采纳答案by Sajeetharan
Below, there's a simple working prototype to generate json from a string instance. Use this code snippet to update your client part. And it should work.
下面是一个从字符串实例生成 json 的简单工作原型。使用此代码片段更新您的客户端部分。它应该工作。
import java.util.Base64;
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// composing string to be encoded
sb.append("Part 1 of some text to be encoded to base64 format\n");
sb.append("Part 2 of some text to be encoded to base64 format\n");
sb.append("Part 3 of some text to be encoded to base64 format");
// getting base64 encoded string bytes
byte[] bytesEncoded = Base64.getEncoder().encode(sb.toString().getBytes());
// composing json
String json = "{\"serialDataByte\":\""+ new String(bytesEncoded) +"\"}";
System.out.println(json);
}
}
UPDATE:
更新:
The code uses Java 8 SDK. If you are using pre-Java8 version, then consider Apache Commons Codecfor this task.
该代码使用 Java 8 SDK。如果您使用的是 Java8 之前的版本,请考虑使用Apache Commons Codec来完成此任务。
Below there's a sample code, that uses Apache Commons Codec for Base64 encoding (please note that import directive has been changed):
下面是一个示例代码,它使用 Apache Commons Codec 进行 Base64 编码(请注意导入指令已更改):
import org.apache.commons.codec.binary.Base64;
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// composing string to be encoded
sb.append("Part 1 of some text to be encoded to base64 format\n");
sb.append("Part 2 of some text to be encoded to base64 format\n");
sb.append("Part 3 of some text to be encoded to base64 format");
// getting base64 encoded string bytes
byte[] bytesEncoded = Base64.encodeBase64(sb.toString().getBytes());
// composing json
String json = "{\"serialDataByte\":\""+ new String(bytesEncoded) +"\"}";
System.out.println(json);
}
}
UPDATE 2:
更新 2:
Upon sending POST requests make sure that you have marked your request as a POST request. Do not forget this line of code, before making the request:
发送 POST 请求后,请确保您已将请求标记为 POST 请求。在发出请求之前,不要忘记这行代码:
connection.setRequestMethod("POST");
and use HttpURLConnection instead of URLConnection:
并使用 HttpURLConnection 而不是 URLConnection:
import java.net.HttpURLConnection;