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”)'? –