0
我試圖推送json數據,它與以下代碼一起工作,但是,當我直接發送json數據時無法獲得所需結果,表示如果用String input = jsonString;將json數據發佈到URL中時出錯
我的JSON字符串構建爲:
ArrayList <ContactData> documents;
Gson g = new Gson();
String jsonString = g.toJson(documents);
然後通過JSON字符串我的方法
private void pushDataToClientURL(String clientURL, String jsonString)
{
try {
log.debug("starting pushing data to Client URL");
URL targetUrl = new URL(clientURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = httpConnection.getOutputStream();
##line1 String input ="{\"statusCode\":1,\"type\":\"Liam\",\"age\":22,\"value\":\"Marco\"}";
outputStream.write(input.getBytes());
outputStream.flush();
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
log.debug("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
這是我的休息服務
@POST
@Path("/dataPosting")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(ContactData bean){
String result = bean.toString();
return Response.status(200).entity(result).build();
}
Getting error
Exception in thread "Thread-3" java.lang.RuntimeException: Failed : HTTP error code : 400
at com.rest.test.profiling.ProfilingDataPushJOB.pushDataToClientURL(ProfilingDataPushJOB.java:127)
at com.rest.test.profiling.ProfilingDataPushJOB.run(ProfilingDataPushJOB.java:93)
at java.lang.Thread.run(Thread.java:745)
如果這將有URL問題,這將無法與我在這裏粘貼的書面代碼,它不僅工作時,我正在替換## line1分配與JSON字符串手段沒有「\」字符在我的字符串 – MAX
你用'StringEntity'試過了嗎?並添加了'setContentType(「application/json」)'? –