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;
    }
}
相關文章
相關標籤/搜索