HttpUtils方法
引入依赖:
<!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <!-- io常用工具类 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency>
/** * 向指定 URL 发送GET方法的请求 * * @param url 发送请求的 URL * @param headerMap 请求头参数,。 * @param paramMap 请求参数,。 * @return 所代表远程资源的响应结果 */ public static String get(String url, Map<String,Object> headerMap, Map<String,Object> paramMap) { String res = null; StringBuilder sb = new StringBuilder(); int i = 0; try { //拼接请求参数 for (Iterator<String> $it = paramMap.keySet().iterator(); $it.hasNext(); i++){ String key = $it.next(); if (i == 0){ sb.append("?"); } else { sb.append("&"); } sb.append(key).append("=").append(paramMap.get(key)); } String apiUrl = url + sb.toString(); System.err.println("apiUrl:"+apiUrl); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(apiUrl); if (null != headerMap){ Iterator<Map.Entry<String, Object>> iterator = headerMap.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String, Object> next = iterator.next(); httpGet.setHeader(next.getKey(), String.valueOf(next.getValue())); } } for (Header allHeader : httpGet.getAllHeaders()) { System.out.println(String.format("%s:%s", allHeader.getName(), allHeader.getValue())); } CloseableHttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200 || statusCode == 201){ InputStream content = response.getEntity().getContent(); res = IOUtils.toString(content, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } return res; }