java实现HTTP请求的三种方式

目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

第一种方式:java原生HttpURLConnection

  1 package com.powerX.httpClient;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.net.HttpURLConnection;
  9 import java.net.MalformedURLException;
 10 import java.net.URL;
 11 
 12 public class HttpClient {
 13     public static String doGet(String httpurl) {
 14         HttpURLConnection connection = null;
 15         InputStream is = null;
 16         BufferedReader br = null;
 17         String result = null;// 返回结果字符串
 18         try {
 19             // 创建远程url连接对象
 20             URL url = new URL(httpurl);
 21             // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
 22             connection = (HttpURLConnection) url.openConnection();
 23             // 设置连接方式:get
 24             connection.setRequestMethod("GET");
 25             // 设置连接主机服务器的超时时间:15000毫秒
 26             connection.setConnectTimeout(15000);
 27             // 设置读取远程返回的数据时间:60000毫秒
 28             connection.setReadTimeout(60000);
 29             // 发送请求
 30             connection.connect();
 31             // 通过connection连接,获取输入流
 32             if (connection.getResponseCode() == 200) {
 33                 is = connection.getInputStream();
 34                 // 封装输入流is,并指定字符集
 35                 br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 36                 // 存放数据
 37                 StringBuffer sbf = new StringBuffer();
 38                 String temp = null;
 39                 while ((temp = br.readLine()) != null) {
 40                     sbf.append(temp);
 41                     sbf.append("
");
 42                 }
 43                 result = sbf.toString();
 44             }
 45         } catch (MalformedURLException e) {
 46             e.printStackTrace();
 47         } catch (IOException e) {
 48             e.printStackTrace();
 49         } finally {
 50             // 关闭资源
 51             if (null != br) {
 52                 try {
 53                     br.close();
 54                 } catch (IOException e) {
 55                     e.printStackTrace();
 56                 }
 57             }
 58 
 59             if (null != is) {
 60                 try {
 61                     is.close();
 62                 } catch (IOException e) {
 63                     e.printStackTrace();
 64                 }
 65             }
 66 
 67             connection.disconnect();// 关闭远程连接
 68         }
 69 
 70         return result;
 71     }
 72 
 73     public static String doPost(String httpUrl, String param) {
 74 
 75         HttpURLConnection connection = null;
 76         InputStream is = null;
 77         OutputStream os = null;
 78         BufferedReader br = null;
 79         String result = null;
 80         try {
 81             URL url = new URL(httpUrl);
 82             // 通过远程url连接对象打开连接
 83             connection = (HttpURLConnection) url.openConnection();
 84             // 设置连接请求方式
 85             connection.setRequestMethod("POST");
 86             // 设置连接主机服务器超时时间:15000毫秒
 87             connection.setConnectTimeout(15000);
 88             // 设置读取主机服务器返回数据超时时间:60000毫秒
 89             connection.setReadTimeout(60000);
 90 
 91             // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
 92             connection.setDoOutput(true);
 93             // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
 94             connection.setDoInput(true);
 95             // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
 96             connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 97             // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
 98             connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
 99             // 通过连接对象获取一个输出流
100             os = connection.getOutputStream();
101             // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
102             os.write(param.getBytes());
103             // 通过连接对象获取一个输入流,向远程读取
104             if (connection.getResponseCode() == 200) {
105 
106                 is = connection.getInputStream();
107                 // 对输入流对象进行包装:charset根据工作项目组的要求来设置
108                 br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
109 
110                 StringBuffer sbf = new StringBuffer();
111                 String temp = null;
112                 // 循环遍历一行一行读取数据
113                 while ((temp = br.readLine()) != null) {
114                     sbf.append(temp);
115                     sbf.append("
");
116                 }
117                 result = sbf.toString();
118             }
119         } catch (MalformedURLException e) {
120             e.printStackTrace();
121         } catch (IOException e) {
122             e.printStackTrace();
123         } finally {
124             // 关闭资源
125             if (null != br) {
126                 try {
127                     br.close();
128                 } catch (IOException e) {
129                     e.printStackTrace();
130                 }
131             }
132             if (null != os) {
133                 try {
134                     os.close();
135                 } catch (IOException e) {
136                     e.printStackTrace();
137                 }
138             }
139             if (null != is) {
140                 try {
141                     is.close();
142                 } catch (IOException e) {
143                     e.printStackTrace();
144                 }
145             }
146             // 断开与远程地址url的连接
147             connection.disconnect();
148         }
149         return result;
150     }
151 }

第二种方式:apache HttpClient3.1

  1 package com.powerX.httpClient;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.UnsupportedEncodingException;
  8 import java.util.Iterator;
  9 import java.util.Map;
 10 import java.util.Map.Entry;
 11 import java.util.Set;
 12 
 13 import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
 14 import org.apache.commons.httpclient.HttpClient;
 15 import org.apache.commons.httpclient.HttpStatus;
 16 import org.apache.commons.httpclient.NameValuePair;
 17 import org.apache.commons.httpclient.methods.GetMethod;
 18 import org.apache.commons.httpclient.methods.PostMethod;
 19 import org.apache.commons.httpclient.params.HttpMethodParams;
 20 
 21 public class HttpClient3 {
 22 
 23     public static String doGet(String url) {
 24         // 输入流
 25         InputStream is = null;
 26         BufferedReader br = null;
 27         String result = null;
 28         // 创建httpClient实例
 29         HttpClient httpClient = new HttpClient();
 30         // 设置http连接主机服务超时时间:15000毫秒
 31         // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
 32         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
 33         // 创建一个Get方法实例对象
 34         GetMethod getMethod = new GetMethod(url);
 35         // 设置get请求超时为60000毫秒
 36         getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
 37         // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
 38         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
 39         try {
 40             // 执行Get方法
 41             int statusCode = httpClient.executeMethod(getMethod);
 42             // 判断返回码
 43             if (statusCode != HttpStatus.SC_OK) {
 44                 // 如果状态码返回的不是ok,说明失败了,打印错误信息
 45                 System.err.println("Method faild: " + getMethod.getStatusLine());
 46             } else {
 47                 // 通过getMethod实例,获取远程的一个输入流
 48                 is = getMethod.getResponseBodyAsStream();
 49                 // 包装输入流
 50                 br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 51 
 52                 StringBuffer sbf = new StringBuffer();
 53                 // 读取封装的输入流
 54                 String temp = null;
 55                 while ((temp = br.readLine()) != null) {
 56                     sbf.append(temp).append("
");
 57                 }
 58 
 59                 result = sbf.toString();
 60             }
 61 
 62         } catch (IOException e) {
 63             e.printStackTrace();
 64         } finally {
 65             // 关闭资源
 66             if (null != br) {
 67                 try {
 68                     br.close();
 69                 } catch (IOException e) {
 70                     e.printStackTrace();
 71                 }
 72             }
 73             if (null != is) {
 74                 try {
 75                     is.close();
 76                 } catch (IOException e) {
 77                     e.printStackTrace();
 78                 }
 79             }
 80             // 释放连接
 81             getMethod.releaseConnection();
 82         }
 83         return result;
 84     }
 85 
 86     public static String doPost(String url, Map<String, Object> paramMap) {
 87         // 获取输入流
 88         InputStream is = null;
 89         BufferedReader br = null;
 90         String result = null;
 91         // 创建httpClient实例对象
 92         HttpClient httpClient = new HttpClient();
 93         // 设置httpClient连接主机服务器超时时间:15000毫秒
 94         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
 95         // 创建post请求方法实例对象
 96         PostMethod postMethod = new PostMethod(url);
 97         // 设置post请求超时时间
 98         postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
 99 
100         NameValuePair[] nvp = null;
101         // 判断参数map集合paramMap是否为空
102         if (null != paramMap && paramMap.size() > 0) {// 不为空
103             // 创建键值参数对象数组,大小为参数的个数
104             nvp = new NameValuePair[paramMap.size()];
105             // 循环遍历参数集合map
106             Set<Entry<String, Object>> entrySet = paramMap.entrySet();
107             // 获取迭代器
108             Iterator<Entry<String, Object>> iterator = entrySet.iterator();
109 
110             int index = 0;
111             while (iterator.hasNext()) {
112                 Entry<String, Object> mapEntry = iterator.next();
113                 // 从mapEntry中获取key和value创建键值对象存放到数组中
114                 try {
115                     nvp[index] = new NameValuePair(mapEntry.getKey(),
116                             new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
117                 } catch (UnsupportedEncodingException e) {
118                     e.printStackTrace();
119                 }
120                 index++;
121             }
122         }
123         // 判断nvp数组是否为空
124         if (null != nvp && nvp.length > 0) {
125             // 将参数存放到requestBody对象中
126             postMethod.setRequestBody(nvp);
127         }
128         // 执行POST方法
129         try {
130             int statusCode = httpClient.executeMethod(postMethod);
131             // 判断是否成功
132             if (statusCode != HttpStatus.SC_OK) {
133                 System.err.println("Method faild: " + postMethod.getStatusLine());
134             }
135             // 获取远程返回的数据
136             is = postMethod.getResponseBodyAsStream();
137             // 封装输入流
138             br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
139 
140             StringBuffer sbf = new StringBuffer();
141             String temp = null;
142             while ((temp = br.readLine()) != null) {
143                 sbf.append(temp).append("
");
144             }
145 
146             result = sbf.toString();
147         } catch (IOException e) {
148             e.printStackTrace();
149         } finally {
150             // 关闭资源
151             if (null != br) {
152                 try {
153                     br.close();
154                 } catch (IOException e) {
155                     e.printStackTrace();
156                 }
157             }
158             if (null != is) {
159                 try {
160                     is.close();
161                 } catch (IOException e) {
162                     e.printStackTrace();
163                 }
164             }
165             // 释放连接
166             postMethod.releaseConnection();
167         }
168         return result;
169     }
170 }

第三种方式:apache  httpClient4.5

  1 package com.powerX.httpClient;
  2 
  3 import java.io.IOException;
  4 import java.io.UnsupportedEncodingException;
  5 import java.util.ArrayList;
  6 import java.util.Iterator;
  7 import java.util.List;
  8 import java.util.Map;
  9 import java.util.Map.Entry;
 10 import java.util.Set;
 11 
 12 import org.apache.http.HttpEntity;
 13 import org.apache.http.NameValuePair;
 14 import org.apache.http.client.ClientProtocolException;
 15 import org.apache.http.client.config.RequestConfig;
 16 import org.apache.http.client.entity.UrlEncodedFormEntity;
 17 import org.apache.http.client.methods.CloseableHttpResponse;
 18 import org.apache.http.client.methods.HttpGet;
 19 import org.apache.http.client.methods.HttpPost;
 20 import org.apache.http.impl.client.CloseableHttpClient;
 21 import org.apache.http.impl.client.HttpClients;
 22 import org.apache.http.message.BasicNameValuePair;
 23 import org.apache.http.util.EntityUtils;
 24 
 25 public class HttpClient4 {
 26 
 27     public static String doGet(String url) {
 28         CloseableHttpClient httpClient = null;
 29         CloseableHttpResponse response = null;
 30         String result = "";
 31         try {
 32             // 通过址默认配置创建一个httpClient实例
 33             httpClient = HttpClients.createDefault();
 34             // 创建httpGet远程连接实例
 35             HttpGet httpGet = new HttpGet(url);
 36             // 设置请求头信息,鉴权
 37             httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
 38             // 设置配置请求参数
 39             RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
 40                     .setConnectionRequestTimeout(35000)// 请求超时时间
 41                     .setSocketTimeout(60000)// 数据读取超时时间
 42                     .build();
 43             // 为httpGet实例设置配置
 44             httpGet.setConfig(requestConfig);
 45             // 执行get请求得到返回对象
 46             response = httpClient.execute(httpGet);
 47             // 通过返回对象获取返回数据
 48             HttpEntity entity = response.getEntity();
 49             // 通过EntityUtils中的toString方法将结果转换为字符串
 50             result = EntityUtils.toString(entity);
 51         } catch (ClientProtocolException e) {
 52             e.printStackTrace();
 53         } catch (IOException e) {
 54             e.printStackTrace();
 55         } finally {
 56             // 关闭资源
 57             if (null != response) {
 58                 try {
 59                     response.close();
 60                 } catch (IOException e) {
 61                     e.printStackTrace();
 62                 }
 63             }
 64             if (null != httpClient) {
 65                 try {
 66                     httpClient.close();
 67                 } catch (IOException e) {
 68                     e.printStackTrace();
 69                 }
 70             }
 71         }
 72         return result;
 73     }
 74 
 75     public static String doPost(String url, Map<String, Object> paramMap) {
 76         CloseableHttpClient httpClient = null;
 77         CloseableHttpResponse httpResponse = null;
 78         String result = "";
 79         // 创建httpClient实例
 80         httpClient = HttpClients.createDefault();
 81         // 创建httpPost远程连接实例
 82         HttpPost httpPost = new HttpPost(url);
 83         // 配置请求参数实例
 84         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
 85                 .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
 86                 .setSocketTimeout(60000)// 设置读取数据连接超时时间
 87                 .build();
 88         // 为httpPost实例设置配置
 89         httpPost.setConfig(requestConfig);
 90         // 设置请求头
 91         httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
 92         // 封装post请求参数
 93         if (null != paramMap && paramMap.size() > 0) {
 94             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 95             // 通过map集成entrySet方法获取entity
 96             Set<Entry<String, Object>> entrySet = paramMap.entrySet();
 97             // 循环遍历,获取迭代器
 98             Iterator<Entry<String, Object>> iterator = entrySet.iterator();
 99             while (iterator.hasNext()) {
100                 Entry<String, Object> mapEntry = iterator.next();
101                 nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
102             }
103 
104             // 为httpPost设置封装好的请求参数
105             try {
106                 httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
107             } catch (UnsupportedEncodingException e) {
108                 e.printStackTrace();
109             }
110         }
111         try {
112             // httpClient对象执行post请求,并返回响应参数对象
113             httpResponse = httpClient.execute(httpPost);
114             // 从响应对象中获取响应内容
115             HttpEntity entity = httpResponse.getEntity();
116             result = EntityUtils.toString(entity);
117         } catch (ClientProtocolException e) {
118             e.printStackTrace();
119         } catch (IOException e) {
120             e.printStackTrace();
121         } finally {
122             // 关闭资源
123             if (null != httpResponse) {
124                 try {
125                     httpResponse.close();
126                 } catch (IOException e) {
127                     e.printStackTrace();
128                 }
129             }
130             if (null != httpClient) {
131                 try {
132                     httpClient.close();
133                 } catch (IOException e) {
134                     e.printStackTrace();
135                 }
136             }
137         }
138         return result;
139     }
140 }

原文转载自  https://www.cnblogs.com/hhhshct/p/8523697.html

原文地址:https://www.cnblogs.com/xiaoyue1606bj/p/11307954.html