• httpclient发送request请求时设置header和timeout


    package com.xxx.xxx.common;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Map;
    
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.HttpResponse;
    
    import com.google.common.base.Charsets;
    
    public class HttpRequest {
        /**
         * 向指定URL发送GET方法的请求
         * 
         * @param url
         *            发送请求的URL
         * @param param
         *            httprequest请求参数。
         * @param headers
         *            需要添加的httpheader参数
         * @param timeout
         *            请求超时时间
         * @return result 所代表远程资源的响应结果
         */
        public static String Get(String url, String param, Map<String, String> headers, int timeout) {
            String result = "";
            BufferedReader in = null;
            String reqUrl = url + "?" + param;
            try {
                // 构造httprequest设置
                RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout)
                        .setConnectionRequestTimeout(timeout).build();
                HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
                HttpGet htGet = new HttpGet(reqUrl);
                // 添加http headers
                if (headers != null && headers.size() > 0) {
                    for (String key : headers.keySet()) {
                        htGet.addHeader(key, headers.get(key));
                    }
                }
                // 读取数据
                HttpResponse r = client.execute(htGet);
                in = new BufferedReader(new InputStreamReader(r.getEntity().getContent(), Charsets.UTF_8));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in = null;
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
    }
  • 相关阅读:
    Tom&Jerry_team——测试总结
    OMCP sprint 第7天
    OMCP sprint 第6天
    OMCP sprint 第5天
    OMCP sprint 第4天
    OMCP sprint 第3天
    OMCP sprint 第2天
    SQL SERVER 如何恢复bak备份文件
    Ext JS
    Linnx环境下常用命令
  • 原文地址:https://www.cnblogs.com/snowlove67/p/4838455.html
Copyright © 2020-2023  润新知