当前位置:   article > 正文

JAVA发送GET和POST请求_java get post

java get post

一、介绍
使用Java实现GET和POST请求的方法常用的有两种:HTTPClient和HttpURLConnection。前者是第三方开源框架实现,对HTTP请求的封装很好,使用HTTPClient基本可以满足工作需要,其中HTTPClient3.1是org.apache.commons.httpclient下操作远程url的工具包,HTTPClient4.5.5是org.apache.http.client下操作远程url的工具包。而HttpURLConnection是java的标准请求方式。

二、实现

1.HttpURLConnection原生实现方式:

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

2.java原生HttpClient3.1

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

3.java原生httpClient4.5

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

传入的参数是json或者其他格式需要更改请求头及参数的设置信息,

httpPost.setEntity(new StringEntity("你的json串"));

httpPost.addHeader("Content-Type", "application/json")。

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

闽ICP备14008679号