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; } }