我正在尝试使用以下代码来推送json数据但是,当我直接发送json数据时,无法获得所需的结果,意味着如果用String input = jsonString替换## line1;
我的json String构造为:
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)
答案 0 :(得分:0)
将您的JSON字符串转换为字符串实体,并将setEntity转换为http post请求。 StringEntity se = new StringEntity(jsonString);