apache HttpClient和HttpURLConnection发送get请求和post请求

Myth丶恋晨 2022-06-02 12:21 330阅读 0赞

apache HttpClient和HttpURLConnection发送get请求和post请求

本文主要介绍如题的两种方式下,如何发送http的get和post请求。

apache HttpClient

  1. package com.xueyou.http;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.ParseException;
  4. import org.apache.http.client.ClientProtocolException;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClients;
  11. import org.apache.http.message.BasicNameValuePair;
  12. import org.apache.http.util.EntityUtils;
  13. import java.io.IOException;
  14. import java.io.UnsupportedEncodingException;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. public class HttpClient {
  18. public static final String GET_URL = "http://www.baidu.com";
  19. public static final String POST_URL = "http://www.baidu.com";
  20. public static void main(String[] args) throws Exception {
  21. getRequest();
  22. postRequest();
  23. }
  24. /**
  25. * post方式提交json代码
  26. *
  27. * @throws Exception
  28. */
  29. public static void getRequest() throws Exception {
  30. CloseableHttpClient httpclient = HttpClients.createDefault();
  31. try {
  32. // 创建httpget.
  33. HttpGet httpget = new HttpGet(GET_URL);
  34. System.out.println("executing request " + httpget.getURI());
  35. // 执行get请求.
  36. CloseableHttpResponse response = httpclient.execute(httpget);
  37. try {
  38. // 获取响应实体
  39. HttpEntity entity = response.getEntity();
  40. System.out.println("--------------------------------------");
  41. // 打印响应状态
  42. System.out.println(response.getStatusLine());
  43. if (entity != null) {
  44. // 打印响应内容长度
  45. System.out.println("Response content length: " + entity.getContentLength());
  46. // 打印响应内容
  47. System.out.println("Response content: " + EntityUtils.toString(entity));
  48. }
  49. System.out.println("------------------------------------");
  50. } finally {
  51. response.close();
  52. }
  53. } catch (ClientProtocolException e) {
  54. e.printStackTrace();
  55. } catch (ParseException e) {
  56. e.printStackTrace();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. } finally {
  60. // 关闭连接,释放资源
  61. try {
  62. httpclient.close();
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }
  68. /**
  69. * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
  70. */
  71. public static void postRequest() {
  72. // 创建默认的httpClient实例.
  73. CloseableHttpClient httpclient = HttpClients.createDefault();
  74. // 创建httppost
  75. HttpPost httppost = new HttpPost(POST_URL);
  76. // 创建参数队列
  77. List formparams = new ArrayList();
  78. formparams.add(new BasicNameValuePair("name", "xiaoming"));
  79. UrlEncodedFormEntity uefEntity;
  80. try {
  81. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  82. httppost.setEntity(uefEntity);
  83. System.out.println("executing request " + httppost.getURI());
  84. CloseableHttpResponse response = httpclient.execute(httppost);
  85. try {
  86. HttpEntity entity = response.getEntity();
  87. if (entity != null) {
  88. System.out.println("--------------------------------------");
  89. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  90. System.out.println("--------------------------------------");
  91. }
  92. } finally {
  93. response.close();
  94. }
  95. } catch (ClientProtocolException e) {
  96. e.printStackTrace();
  97. } catch (UnsupportedEncodingException e1) {
  98. e1.printStackTrace();
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. } finally {
  102. // 关闭连接,释放资源
  103. try {
  104. httpclient.close();
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. }
  108. }
  109. }
  110. }

HttpURLConnection方式

  1. package com.xueyou.http;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.HashMap;
  9. public class URLConnectionClient {
  10. private final static String HTTP_URL_GET = "http://www.baidu.com";
  11. private final static String HTTP_URL_POST = "http://www.baidu.com";
  12. private static HashMap<String, String> mData = new HashMap<String, String>();
  13. public static void main(String[] args) throws Exception {
  14. mData.put("name", "HongBin");
  15. mData.put("sex", "male");
  16. System.out.println("GetResult:" + startGet(HTTP_URL_GET));
  17. System.out.println("PostResult:" + startPost(HTTP_URL_POST));
  18. }
  19. private static String startGet(String path) {
  20. BufferedReader in = null;
  21. StringBuilder result = new StringBuilder();
  22. try {
  23. //GET请求直接在链接后面拼上请求参数
  24. String mPath = path + "?";
  25. for (String key : mData.keySet()) {
  26. mPath += key + "=" + mData.get(key) + "&";
  27. }
  28. mPath = mPath.substring(0, mPath.length() - 1);
  29. URL url = new URL(mPath);
  30. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  31. conn.setRequestMethod("GET");
  32. //Get请求不需要DoOutPut
  33. conn.setDoOutput(false);
  34. conn.setDoInput(true);
  35. //设置连接超时时间和读取超时时间
  36. conn.setConnectTimeout(10000);
  37. conn.setReadTimeout(10000);
  38. // String routeCode = conn.getRequestProperty("routeCode");
  39. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  40. //连接服务器
  41. conn.connect();
  42. // 取得输入流,并使用Reader读取
  43. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  44. String line;
  45. while ((line = in.readLine()) != null) {
  46. result.append(line);
  47. }
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. //关闭输入流
  52. finally {
  53. try {
  54. if (in != null) {
  55. in.close();
  56. }
  57. } catch (IOException ex) {
  58. ex.printStackTrace();
  59. }
  60. }
  61. return result.toString();
  62. }
  63. private static String startPost(String path) {
  64. OutputStreamWriter out = null;
  65. BufferedReader in = null;
  66. StringBuilder result = new StringBuilder();
  67. try {
  68. URL url = new URL(path);
  69. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  70. conn.setRequestMethod("POST");
  71. // 发送POST请求必须设置为true
  72. conn.setDoOutput(true);
  73. conn.setDoInput(true);
  74. //设置连接超时时间和读取超时时间
  75. conn.setConnectTimeout(10000);
  76. conn.setReadTimeout(10000);
  77. conn.setRequestProperty("Content-Type", "x-www-form-urlencoded");
  78. out = new OutputStreamWriter(conn.getOutputStream());
  79. // POST的请求参数写在正文中
  80. for (String key : mData.keySet()) {
  81. out.write(key + "=" + mData.get(key) + "&");
  82. }
  83. out.flush();
  84. out.close();
  85. // 取得输入流,并使用Reader读取
  86. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  87. String line;
  88. while ((line = in.readLine()) != null) {
  89. result.append(line);
  90. }
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. }
  94. //关闭输出流、输入流
  95. finally {
  96. try {
  97. if (out != null) {
  98. out.close();
  99. }
  100. if (in != null) {
  101. in.close();
  102. }
  103. } catch (IOException ex) {
  104. ex.printStackTrace();
  105. }
  106. }
  107. return result.toString();
  108. }
  109. }

发表评论

表情:
评论列表 (有 0 条评论,330人围观)

还没有评论,来说两句吧...

相关阅读