使用 httpclientcomponents 向服务器发送 JSON 请求
Send a JSON request to a server with httpclientcomponents
此代码工作正常...因为我对此进行了很多搜索,所以我决定将此代码用于想要向具有 URL 的服务器发送 json 请求的人
.这是HttpClientComponent
public static boolean sendJsonTo(String URL,JSONObject jo) throws IOException {
CloseableHttpClient httpClient= HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost(URL);
StringEntity params = new StringEntity(jo.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response=httpClient.execute(request);
} catch (Exception ex) {
ex.printStackTrace();
return false;
// handle exception here
} finally {
httpClient.close();
}
return true;
}
我正在使用 this json version
并且这是 make json Object
的示例代码
public static JSONObject test(String firstname,String lastname){
JSONObject jup=new JSONObject();
jup.put("fname",firstname);
jup.put("lname",lastname);
return jup;
}
处理来自服务器的响应:
试试这个:
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
或者像这样
HttpEntity entity = response.getEntity();
JsonFactory jsonf = new JsonFactory();
// try with resource is not strictly necessary here
// but is a good practice
try(InputStream instream = entity.getContent()) { JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
}
此代码工作正常...因为我对此进行了很多搜索,所以我决定将此代码用于想要向具有 URL 的服务器发送 json 请求的人 .这是HttpClientComponent
public static boolean sendJsonTo(String URL,JSONObject jo) throws IOException {
CloseableHttpClient httpClient= HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost(URL);
StringEntity params = new StringEntity(jo.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response=httpClient.execute(request);
} catch (Exception ex) {
ex.printStackTrace();
return false;
// handle exception here
} finally {
httpClient.close();
}
return true;
}
我正在使用 this json version
并且这是 make json Object
的示例代码public static JSONObject test(String firstname,String lastname){
JSONObject jup=new JSONObject();
jup.put("fname",firstname);
jup.put("lname",lastname);
return jup;
}
处理来自服务器的响应:
试试这个:
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
或者像这样
HttpEntity entity = response.getEntity();
JsonFactory jsonf = new JsonFactory();
// try with resource is not strictly necessary here
// but is a good practice
try(InputStream instream = entity.getContent()) { JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
}