使用httpclientcomponents向服务器发送JSON请求

时间:2015-12-27 12:57:02

标签: java apache-httpclient-4.x

此代码正常工作...因为我有很多搜索这个,所以我决定把这个代码放在想要发送json请求的代码到带有URL的服务器上 这是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;
}

1 个答案:

答案 0 :(得分:2)

处理来自服务器的响应:
试试这个:

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;
    }