HttpClient发送get 、post请求json

使用HttpClient发送请求的一般步骤
(1) 创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3) 如果需要发送请求参数,可调用HttpGet同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4) 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5) 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。无论执行方法是否成功,都必须释放连接

HTTP的三种超时说明

1.connectionRequestTimout

指从连接池获取连接的timeout

2.connetionTimeout

指客户端和服务器建立连接的timeout,
就是http请求的三个阶段,一:建立连接;二:数据传送;三,断开连接。超时后会ConnectionTimeOutException

3.socketTimeout

指客户端和服务器建立连接后,客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException

Get请求和Post请求其实只是HttpGet和HttpPost的区别Get的参数是跟在路径后面的而post的请求是需要

Post请求

        String url = "请求路径如:http://www.baidu.com";
        HttpClient httpClient = null;
        HttpPost postMethod = null;
        HttpResponse response = null;
        RebackTokenEntity rebackTokenEntity = null;
        /*设置连接超时时间*/
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectionRequestTimeout(10000).
                setConnectTimeout(10000).
                setSocketTimeout(10000).
                build();
        postMethod.setConfig(requestConfig);
        try {
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);//传入URL地址
            //设置请求头 指定为json
            postMethod.addHeader("Content-type", "application/json;charset=UTF-8");
            //传入请求参数 Class为我传入的对象参数
            postMethod.setEntity(new StringEntity(Class.toString(), Charset.forName("UTF-8")));
            response = httpClient.execute(postMethod);//获取响应

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
            }
            HttpEntity httpEntity = response.getEntity();
            String reponseContent = EntityUtils.toString(httpEntity,"UTF-8");
            EntityUtils.consume(httpEntity);//释放资源
            //用Gson将对象转化为实体类
            Gson gson = new Gson();
            Class= gson.fromJson(reponseContent, Class.class);

            System.out.println("响应内容:" + reponseContent);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            /*关闭连接资源*/
            try {
                if (response == null){
                    response.getEntity().getContent().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

Post请求Map传参

private static String doPost(String url, Map<String, Object> paramMap) {
    String res = null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        postMethod.addParameter(next.getKey(), next.getValue().toString());
    }
    try {
        int code = client.executeMethod(postMethod);
        if (code == 200) {
            res = postMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

Get请求

        String url = "请求路径如:http://xxx?name=zhangsan&age=18";
        HttpClient httpClient = null;
        HttpGet GetMethod = null;
        HttpResponse response = null;
        RebackTokenEntity rebackTokenEntity = null;
        /*设置连接超时时间*/
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectionRequestTimeout(10000).
                setConnectTimeout(10000).
                setSocketTimeout(10000).
                build();
        GetMethod.setConfig(requestConfig);
        try {
            httpClient = HttpClients.createDefault();
            GetMethod = new HttpGet(url);//传入URL地址
            //设置请求头
            GetMethod.addHeader("Content-type", "application/json;charset=UTF-8");
            response = httpClient.execute(GetMethod);//获取响应

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
            }
            HttpEntity httpEntity = response.getEntity();
            String reponseContent = EntityUtils.toString(httpEntity,"UTF-8");
            EntityUtils.consume(httpEntity);//释放资源

            Gson gson = new Gson();
            Class= gson.fromJson(reponseContent, Class.class);

            System.out.println("响应内容:" + reponseContent);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            /*关闭连接资源*/
            try {
                if (response == null){
                    response.getEntity().getContent().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

注:httpclient建立连接后主动close释放资源,避免thread pool is full

此处是抄袭原作者地址:
httpclient建立连接后主动close释放资源,避免thread pool is full

最近遇到线上机器的日志报错:error message:[]Error log: thread pool is full
定位原因是httpclient创建连接后没有及时关闭,为了关闭连接,特意找到了两种关闭连接的方法

方法1:关闭CloseableHttpResponse (推荐)

 * Closes this stream and releases any system resources associated
 * with it. If the stream is already closed then invoking this
 * method has no effect.

close方法解释:关闭此流并释放与其关联的所有系统资源。 如果流已经关闭,则调用此方法无效

public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
	// 释放资源
	if (httpResponse != null) {
		httpResponse.close();
	}
	if (httpClient != null) {
		httpClient.close();
	}
}

方法2:不能直接close时,可使用response.getEntity().getContent().close()
可关闭此输入流并释放与该流关联的所有系统资源
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值