首页 > Web开发 > 详细

httpclient

时间:2020-05-26 18:35:16      阅读:35      评论:0      收藏:0      [点我收藏+]
{

    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static RequestConfig config = null;
    static {
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(2048);
        //可以细分每一个域名最大的连接数
        connectionManager.setDefaultMaxPerRoute(512);

        //设置请求参数
        config = RequestConfig.custom().setConnectTimeout(2000) //连接超时时间
                .setConnectionRequestTimeout(500) //从线程池中获取线程超时时间
                .setSocketTimeout(2000) //设置数据超时时间
                .build();
    }

    public static String postMothed(String url){
        return postMothed(url,null);
    }
    public static String postMothed(String url, Map<String,String> params){
        HttpPost httpPost = new HttpPost(url);
        if(params != null) {
            List list = new ArrayList();
            for(String k : params.keySet()){
                list.add(new BasicNameValuePair(k, params.get(k)));
            }
            HttpEntity requestEntity = null;
            try {
                requestEntity = new UrlEncodedFormEntity(list, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            httpPost.setEntity(requestEntity);
        }
        return executeHttpClient(httpPost);
    }
    public static String getMothed(String url){
        HttpGet httpGet = new HttpGet(url);

        return executeHttpClient(httpGet);
    }
    private static String executeHttpClient(HttpRequestBase httpRequest){

        String content = null;
        //从连接池取httpclient
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

        httpRequest.setConfig(config);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpRequest);
            //根据http code做业务判断
            System.out.println(response.getStatusLine().getStatusCode());
            content = EntityUtils.toString(response.getEntity(), "utf-8");
            //System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;

    }

    public static void main(String[] args) throws IOException {


    }


}

 

httpclient

原文:https://www.cnblogs.com/zzti08/p/12967102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!