How to POST JSON request using Apache HttpClient?

前端 未结 3 1708

I have something like the following:

final String url = \"http://example.com\";

final HttpClient httpClient = new HttpClient();
final PostMethod postMethod          


        
3条回答
  •  被撕碎了的回忆
    2020-12-04 11:42

    For Apache HttpClient 4.5 or newer version:

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://targethost/login");
        String JSON_STRING="";
        HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
    

    Note:

    1 in order to make the code compile, both httpclient package and httpcore package should be imported.

    2 try-catch block has been ommitted.

    Reference: appache official guide

    the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

提交回复
热议问题