笔试题--给定目标url以及请求json参数的情况下,使用httpclient post方式发送json请求到目标url

给定目标url以及请求json参数的情况下,使用httpclient post方式发送json请求到目标url。
使用httpclient如下版本:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>

/**
* 代码模板
*
* @param url post请求地址
* @param jsonBody json内容实体字符串
*/
private void doPost(String url, String jsonBody) {
}

    /**
     * 代码模板
     *
     * @param url      post请求地址
     * @param jsonBody json内容实体字符串
     */
    private void doPost(String url, String jsonBody) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(jsonBody, Charsets.UTF_8));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            System.out.println("请求返回结果为:" + response.getStatusLine().getStatusCode());
            response.close();
            httpClient.close();
        } catch (IOException e) {
            System.out.println("请求出现异常:"  + response.getStatusLine().getStatusCode());
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                System.out.println("请求关闭异常");
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/cnndevelop/p/12221128.html