当前位置:   article > 正文

Java实现HTTP协议发送的三种方式_java 如何使用传输httpentity

java 如何使用传输httpentity

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

 

第二种方式:apache HttpClient3.1

 

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

 

第三种方式:apache  httpClient4.5

 

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

 

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/302831
推荐阅读
相关标签
  

闽ICP备14008679号