背景:
在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。 HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求,POST请求它在URLConnection的基础上提供了如下便捷的方法:
int getResponseCode():获取服务器的响应代码。
String getResponseMessage():获取服务器的响应消息。
String getResponseMethod():获取发送请求的方法。
void setRequestMethod(String method):设置发送请求的方法。
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可以实现的,只是处理起来会变得比较麻烦。为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码,也不会对页面内容进行任何解析、处理。
简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。
使用HttpURLConnection 发送POST请求
1 /**
2 *使用HttpURLConnection 发送post,get请求
3 * @param url http接口地址
4 * @param param 接口拼接请求参数
5 * @return 响应报文/异常报文
6 */
7
8 public static Map<String,Object> sendHttpByPost(String url,String param){
9 Map<String,Object> map = new HashMap<String, Object>();
10 BufferedReader in = null;
11 OutputStreamWriter out = null;
12 String result = "";
13
14 try {
15
16 URL realURL = new URL(url);
17 HttpURLConnection conn = (HttpURLConnection) realURL.openConnection();
18
19 conn.setRequestProperty("accept", "*/*");
20 conn.setRequestProperty("connection", "Keep-Alive");
21 //设置请求方式POST、GET
22 conn.setRequestMethod("POST");
23 conn.setReadTimeout(50000);
24 conn.setConnectTimeout(50000);
25 conn.setDoOutput(true);
26 conn.setDoInput(true);
27
28 //获取对应的输出流
29 out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");
30
31 //发送请求参数
32 out.write(param);
33 out.flush();
34
35 //读取响应
36 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
37
38 String line = "";
39 while((line = in.readLine()) != null){
40 result += line ;
41 }
42
43 if(CommUtil.isNotEmpty(result)){
44 map.put("code", Contants.HTTP_OK);
45 }else {
46 map.put("code", Contants.HTTP_BACK_EXCEPTION);
47 }
48 map.put("message", result);
49
50 } catch (Exception e){
51 map.put("code", Contants.HTTP_NO_RESPONSE);
52 map.put("message", e.getMessage());
53 } finally {
54 try {
55 if(out != null) out.close();
56 } catch(Exception ex){
57 map.put("code", Contants.HTTP_CLOSE_IO_EXCEPTION);
58 map.put("message",ex.getMessage());
59 }
60 }
61
62 return map;
63 }
使用HttpClient 发送POST请求
用HttpClient简单实现工具类
需要在Maven引入配置:
1 <dependency>
2 <groupId>org.apache.httpcomponents</groupId>
3 <artifactId>httpclient</artifactId>
4 <version>4.5.1</version>
5</dependency>
发送POST请求工具类如下:
1 /**
2 *使用 HttpClient 发送post,get 请求
3 * @param url
4 * @return map 响应报文/异常报文
5 */
6 public static Map<String,Object> sendByHttpClient(String url,String param){
7 Map<String,Object> map = new HashMap<String, Object>();
8 HttpPost post = null;
9
10 try {
11 //1、创建HttpClient对象
12 DefaultHttpClient httpClient = new DefaultHttpClient();
13// HttpClient httpClient = new DefaultHttpClient();
14// HttpClient httpClient = HttpClientBuilder.create().build();
15
16 //2、创建HttpGet(HttpPost)对象
17// HttpGet httpGet = new HttpGet(url);
18 post = new HttpPost(url);
19
20 //3、添加请求参数(设置超时时间)
21 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
22 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
23 //设置失败重连http
24 httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0,false));
25
26 //构造消息头
27 post.setHeader("Content-type", "application/json; charset=utf-8");
28 post.setHeader("Connection", "Close");
29
30 //构造消息体
31 StringEntity entity = new StringEntity(param, Charset.forName("UTF-8"));
32 entity.setContentEncoding("UTF-8");
33 //发送json格式的数据请求
34 entity.setContentType("application/json");
35 post.setEntity(entity);
36
37 //4、获取响应,并从HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器响应内容
38 HttpResponse response = httpClient.execute(post);
39
40 map.put("code", response.getStatusLine().getStatusCode());
41 map.put("message", EntityUtils.toString(response.getEntity()));
42
43 } catch(Exception e){
44 map.put("code", Contants.HTTP_BACK_EXCEPTION);
45 map.put("message", "接口返回异常");
46 } finally {
47
48 try {
49 if(post != null){
50 post.releaseConnection();
51 }
52 } catch(Exception e){
53 map.put("code", Contants.HTTP_CLOSE_IO_EXCEPTION);
54 map.put("message", "接口关闭流异常");
55 }
56 }
57 return map;
58 }






