HttpClient4.5常用设置

目前需要设置个超时时间:

    RequestConfig requestConfig = RequestConfig.custom()  
                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
                    .setSocketTimeout(5000).build();  
    httpPost.setConfig(requestConfig);  
    //httpGet.setConfig(requestConfig);

即可。


HttpPost

     * http post请求
     * 
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String post(String url, String jsonBody) throws Exception {
        CloseableHttpClient client = null;// Http客户端
        CloseableHttpResponse response = null;// Http响应

        // JSON实体
        StringEntity entity = new StringEntity(jsonBody, "utf-8");
        entity.setContentType("application/json");

        client = HttpClients.createDefault();// 初始化客户端
        // Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        //设置请求参数
        RequestConfig requestConfig = RequestConfig.custom()  
                .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
                .setSocketTimeout(5000).build();  
        httpPost.setConfig(requestConfig);  

        // 获取响应信息
        response = client.execute(httpPost);

        // 读取响应的字节流
        InputStream inputStream = response.getEntity().getContent();
        StringBuffer buffer = new StringBuffer();
        InputStreamReader inputReader = new InputStreamReader(inputStream);
        BufferedReader bufferReader = new BufferedReader(inputReader);
        String str = new String("");
        while ((str = bufferReader.readLine()) != null) {
            buffer.append(str + "\n");
        }

        String message = buffer.toString();
        // 关闭输出链接等
        if (bufferReader != null)
            bufferReader.close();
        if (inputStream != null)
            inputStream.close();
        if (response != null)
            response.close();
        if (client != null)
            client.close();

        return message;
    }

此处应该try catch finanny里面关闭。


2017-06-15更新:

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.concurrent.Callable;


public static String doPost(String url, Object body) {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(JSON.toJSONString(body)));
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000)
                .build();
        httpPost.setConfig(requestConfig);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(
                    final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                String resBody = entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                HttpClientUtils.closeQuietly(response);

                if (status >= 200 && status < 300) {
                    return resBody;
                } else {
                    throw new IOException("Unexpected response status: " + status + ", message: " + resBody);
                }
            }
        };
        result = httpclient.execute(httpPost, responseHandler);
    } catch (Exception e) {
        logger.error("do post error, url {}, body {}, e {}", url, body, e.getMessage(), e);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
        return result;
    }
}

这个responseHandler比之前的流式读取完美多了!也可以用在get等其他操作。apache都封装好了,very nice!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值