首页 > 代码库 > 【JAVA】通过HttpClient发送HTTP请求的方法
【JAVA】通过HttpClient发送HTTP请求的方法
HttpClient介绍
HttpClient 不是一个浏览器。它是一个客户端的 HTTP 通信实现库。HttpClient的目标是发 送和接收HTTP 报文。HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能。
HttpClient使用
- 使用需要引入jar包,maven项目引入如下:
1 <dependency> 2 <groupId>org.apache.httpcomponents</groupId> 3 <artifactId>httpclient</artifactId> 4 <version>4.5</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.apache.httpcomponents</groupId> 9 <artifactId>httpcore</artifactId> 10 <version>4.4.4</version> 11 </dependency> 12 13 <dependency> 14 <groupId>org.apache.httpcomponents</groupId> 15 <artifactId>httpmime</artifactId> 16 <version>4.5</version> 17 </dependency>
- 使用方法,代码如下:
1 package com.test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Iterator; 6 import java.util.List; 7 import java.util.Map; 8 9 import org.apache.http.HttpEntity; 10 import org.apache.http.HttpStatus; 11 import org.apache.http.client.config.RequestConfig; 12 import org.apache.http.client.methods.CloseableHttpResponse; 13 import org.apache.http.client.methods.HttpGet; 14 import org.apache.http.client.methods.HttpPost; 15 import org.apache.http.entity.ContentType; 16 import org.apache.http.entity.StringEntity; 17 import org.apache.http.entity.mime.MultipartEntityBuilder; 18 import org.apache.http.entity.mime.content.FileBody; 19 import org.apache.http.entity.mime.content.StringBody; 20 import org.apache.http.impl.client.CloseableHttpClient; 21 import org.apache.http.impl.client.HttpClientBuilder; 22 import org.apache.http.impl.client.HttpClients; 23 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 24 import org.apache.http.util.EntityUtils; 25 26 /** 27 * 28 * @author H__D 29 * @date 2016年10月19日 上午11:27:25 30 * 31 */ 32 public class HttpClientUtil { 33 34 // utf-8字符编码 35 public static final String CHARSET_UTF_8 = "utf-8"; 36 37 // HTTP内容类型。 38 public static final String CONTENT_TYPE_TEXT_HTML = "text/xml"; 39 40 // HTTP内容类型。相当于form表单的形式,提交数据 41 public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded"; 42 43 // HTTP内容类型。相当于form表单的形式,提交数据 44 public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8"; 45 46 47 // 连接管理器 48 private static PoolingHttpClientConnectionManager pool; 49 50 // 请求配置 51 private static RequestConfig requestConfig; 52 53 static { 54 pool = new PoolingHttpClientConnectionManager(); 55 // 设置连接池的最大连接数 56 pool.setMaxTotal(50); 57 // 设置每个路由的最大连接数,默认是2 58 pool.setDefaultMaxPerRoute(5); 59 60 // 设置请求超时时间 61 requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000) 62 .setConnectionRequestTimeout(50000).build(); 63 } 64 65 public static CloseableHttpClient getHttpClient() { 66 // 从连接池中获取httpclient 67 return HttpClientBuilder.create().setConnectionManager(pool).build(); 68 } 69 70 /** 71 * 发送Post请求 72 * 73 * @param httpPost 74 * @return 75 */ 76 private static String sendHttpPost(HttpPost httpPost) { 77 78 CloseableHttpClient httpClient = null; 79 CloseableHttpResponse response = null; 80 // 响应内容 81 String responseContent = null; 82 try { 83 // 创建默认的httpClient实例. 84 httpClient = HttpClients.createDefault(); 85 // 配置请求信息 86 httpPost.setConfig(requestConfig); 87 // 执行请求 88 response = httpClient.execute(httpPost); 89 // 得到响应实例 90 HttpEntity entity = response.getEntity(); 91 92 // 可以获得响应头 93 // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); 94 // for (Header header : headers) { 95 // System.out.println(header.getName()); 96 // } 97 98 // 得到响应类型 99 // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType()); 100 101 // 判断响应状态 102 if (response.getStatusLine().getStatusCode() >= 300) { 103 throw new Exception( 104 "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); 105 } 106 107 if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { 108 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); 109 } 110 111 } catch (Exception e) { 112 e.printStackTrace(); 113 } finally { 114 try { 115 // 关闭连接,释放资源 116 if (response != null) { 117 response.close(); 118 } 119 if (httpClient != null) { 120 httpClient.close(); 121 } 122 } catch (IOException e) { 123 e.printStackTrace(); 124 } 125 } 126 return responseContent; 127 } 128 129 /** 130 * 发送Get请求 131 * 132 * @param httpGet 133 * @return 134 */ 135 private static String sendHttpGet(HttpGet httpGet) { 136 137 CloseableHttpClient httpClient = null; 138 CloseableHttpResponse response = null; 139 // 响应内容 140 String responseContent = null; 141 try { 142 // 创建默认的httpClient实例. 143 httpClient = HttpClients.createDefault(); 144 // 配置请求信息 145 httpGet.setConfig(requestConfig); 146 // 执行请求 147 response = httpClient.execute(httpGet); 148 // 得到响应实例 149 HttpEntity entity = response.getEntity(); 150 151 // 可以获得响应头 152 // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); 153 // for (Header header : headers) { 154 // System.out.println(header.getName()); 155 // } 156 157 // 得到响应类型 158 // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType()); 159 160 // 判断响应状态 161 if (response.getStatusLine().getStatusCode() >= 300) { 162 throw new Exception( 163 "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); 164 } 165 166 if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { 167 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); 168 } 169 170 } catch (Exception e) { 171 e.printStackTrace(); 172 } finally { 173 try { 174 // 关闭连接,释放资源 175 if (response != null) { 176 response.close(); 177 } 178 if (httpClient != null) { 179 httpClient.close(); 180 } 181 } catch (IOException e) { 182 e.printStackTrace(); 183 } 184 } 185 return responseContent; 186 } 187 188 189 190 /** 191 * 发送 post请求 192 * 193 * @param httpUrl 194 * 地址 195 */ 196 public static String sendHttpPost(String httpUrl) { 197 // 创建httpPost 198 HttpPost httpPost = new HttpPost(httpUrl); 199 return sendHttpPost(httpPost); 200 } 201 202 /** 203 * 发送 get请求 204 * 205 * @param httpUrl 206 */ 207 public static String sendHttpGet(String httpUrl) { 208 // 创建get请求 209 HttpGet httpGet = new HttpGet(httpUrl); 210 return sendHttpGet(httpGet); 211 } 212 213 214 215 /** 216 * 发送 post请求(带文件) 217 * 218 * @param httpUrl 219 * 地址 220 * @param maps 221 * 参数 222 * @param fileLists 223 * 附件 224 */ 225 public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) { 226 HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost 227 MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); 228 if (maps != null) { 229 for (String key : maps.keySet()) { 230 meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); 231 } 232 } 233 if (fileLists != null) { 234 for (File file : fileLists) { 235 FileBody fileBody = new FileBody(file); 236 meBuilder.addPart("files", fileBody); 237 } 238 } 239 HttpEntity reqEntity = meBuilder.build(); 240 httpPost.setEntity(reqEntity); 241 return sendHttpPost(httpPost); 242 } 243 244 /** 245 * 发送 post请求 246 * 247 * @param httpUrl 248 * 地址 249 * @param params 250 * 参数(格式:key1=value1&key2=value2) 251 * 252 */ 253 public static String sendHttpPost(String httpUrl, String params) { 254 HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost 255 try { 256 // 设置参数 257 if (params != null && params.trim().length() > 0) { 258 StringEntity stringEntity = new StringEntity(params, "UTF-8"); 259 stringEntity.setContentType(CONTENT_TYPE_FORM_URL); 260 httpPost.setEntity(stringEntity); 261 } 262 } catch (Exception e) { 263 e.printStackTrace(); 264 } 265 return sendHttpPost(httpPost); 266 } 267 268 /** 269 * 发送 post请求 270 * 271 * @param maps 272 * 参数 273 */ 274 public static String sendHttpPost(String httpUrl, Map<String, String> maps) { 275 String parem = convertStringParamter(maps); 276 return sendHttpPost(httpUrl, parem); 277 } 278 279 280 281 282 /** 283 * 发送 post请求 发送json数据 284 * 285 * @param httpUrl 286 * 地址 287 * @param paramsJson 288 * 参数(格式 json) 289 * 290 */ 291 public static String sendHttpPostJson(String httpUrl, String paramsJson) { 292 HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost 293 try { 294 // 设置参数 295 if (paramsJson != null && paramsJson.trim().length() > 0) { 296 StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8"); 297 stringEntity.setContentType(CONTENT_TYPE_JSON_URL); 298 httpPost.setEntity(stringEntity); 299 } 300 } catch (Exception e) { 301 e.printStackTrace(); 302 } 303 return sendHttpPost(httpPost); 304 } 305 306 /** 307 * 发送 post请求 发送xml数据 308 * 309 * @param httpUrl 地址 310 * @param paramsXml 参数(格式 Xml) 311 * 312 */ 313 public static String sendHttpPostXml(String httpUrl, String paramsXml) { 314 HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost 315 try { 316 // 设置参数 317 if (paramsXml != null && paramsXml.trim().length() > 0) { 318 StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8"); 319 stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML); 320 httpPost.setEntity(stringEntity); 321 } 322 } catch (Exception e) { 323 e.printStackTrace(); 324 } 325 return sendHttpPost(httpPost); 326 } 327 328 329 /** 330 * 将map集合的键值对转化成:key1=value1&key2=value2 的形式 331 * 332 * @param parameterMap 333 * 需要转化的键值对集合 334 * @return 字符串 335 */ 336 public static String convertStringParamter(Map parameterMap) { 337 StringBuffer parameterBuffer = new StringBuffer(); 338 if (parameterMap != null) { 339 Iterator iterator = parameterMap.keySet().iterator(); 340 String key = null; 341 String value = http://www.mamicode.com/null; 342 while (iterator.hasNext()) { 343 key = (String) iterator.next(); 344 if (parameterMap.get(key) != null) { 345 value =http://www.mamicode.com/ (String) parameterMap.get(key); 346 } else { 347 valuehttp://www.mamicode.com/= ""; 348 } 349 parameterBuffer.append(key).append("=").append(value); 350 if (iterator.hasNext()) { 351 parameterBuffer.append("&"); 352 } 353 } 354 } 355 return parameterBuffer.toString(); 356 } 357 358 public static void main(String[] args) throws Exception { 359 360 System.out.println(sendHttpGet("http://www.baidu.com")); 361 } 362 }
【JAVA】通过HttpClient发送HTTP请求的方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。