Http请求

快来打我* 2022-04-04 13:58 436阅读 0赞
  1. package fun.lovey.http;
  2. import java.io.*;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.util.List;
  6. import java.util.Map;
  7. /**
  8. * java net package
  9. *
  10. * @author liwc
  11. * @version V1.0
  12. * @date 2018-06-25 10:51
  13. */
  14. public class HttpRequestTool {
  15. /**
  16. * 向指定URL发送GET方法的请求
  17. *
  18. * @param url 发送请求的URL
  19. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  20. * @return URL 所代表远程资源的响应结果
  21. */
  22. public static String sendJsonGet(String url, String param) {
  23. String result = "";
  24. BufferedReader in = null;
  25. try {
  26. String urlNameString = url + "?" + param;
  27. URL realUrl = new URL(urlNameString);
  28. // 打开和URL之间的连接
  29. HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
  30. connection.setRequestMethod("GET");
  31. // 设置通用的请求属性
  32. connection.setRequestProperty("accept", "*/*");
  33. connection.setRequestProperty("connection", "Keep-Alive");
  34. connection.setRequestProperty("user-agent",
  35. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  36. // 建立实际的连接
  37. connection.connect();
  38. // 获取所有响应头字段
  39. Map<String, List<String>> map = connection.getHeaderFields();
  40. // 遍历所有的响应头字段
  41. for (String key : map.keySet()) {
  42. System.out.println(key + "--->" + map.get(key));
  43. }
  44. // 定义 BufferedReader输入流来读取URL的响应
  45. in = new BufferedReader(new InputStreamReader(
  46. connection.getInputStream()));
  47. String line = "";
  48. while ((line = in.readLine()) != null) {
  49. result += line;
  50. }
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. }
  54. // 使用finally块来关闭输入流
  55. finally {
  56. try {
  57. if (in != null) {
  58. in.close();
  59. }
  60. } catch (Exception e2) {
  61. e2.printStackTrace();
  62. }
  63. }
  64. return result;
  65. }
  66. /**
  67. * 向指定 URL 发送POST方法的请求
  68. *
  69. * @param url 发送请求的 URL
  70. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  71. * @return 所代表远程资源的响应结果
  72. */
  73. public static String sendPost(String url, String param) {
  74. PrintWriter out = null;
  75. BufferedReader in = null;
  76. String result = "";
  77. try {
  78. URL realUrl = new URL(url);
  79. // 打开和URL之间的连接
  80. HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
  81. // 设置通用的请求属性
  82. conn.setRequestMethod("POST");
  83. conn.setRequestProperty("accept", "*/*");
  84. conn.setRequestProperty("connection", "Keep-Alive");
  85. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  86. // 发送POST请求必须设置如下两行
  87. conn.setDoOutput(true);
  88. conn.setDoInput(true);
  89. // 获取URLConnection对象对应的输出流
  90. out = new PrintWriter(conn.getOutputStream());
  91. // 发送请求参数
  92. out.print(param);
  93. // flush输出流的缓冲
  94. out.flush();
  95. // 定义BufferedReader输入流来读取URL的响应
  96. in = new BufferedReader(
  97. new InputStreamReader(conn.getInputStream()));
  98. String line;
  99. while ((line = in.readLine()) != null) {
  100. result += line;
  101. }
  102. } catch (Exception e) {
  103. System.out.println("发送 POST 请求出现异常!" + e);
  104. e.printStackTrace();
  105. }
  106. //使用finally块来关闭输出流、输入流
  107. finally {
  108. try {
  109. if (out != null) {
  110. out.close();
  111. }
  112. if (in != null) {
  113. in.close();
  114. }
  115. } catch (IOException ex) {
  116. ex.printStackTrace();
  117. }
  118. }
  119. return result;
  120. }
  121. /**
  122. * 发送post表单请求
  123. *
  124. * @param url
  125. * @param params
  126. * @return
  127. */
  128. public static String httpForm(String url, Map<String, String> params) {
  129. URL u = null;
  130. HttpURLConnection con = null;
  131. // 构建请求参数
  132. StringBuffer sb = new StringBuffer();
  133. if (params != null) {
  134. params.forEach((x, y) -> {
  135. sb.append(x);
  136. sb.append("=");
  137. sb.append(y);
  138. sb.append("&");
  139. });
  140. sb.substring(0, sb.length() - 1);
  141. }
  142. System.out.println("send_url:" + url);
  143. System.out.println("send_data:" + sb.toString());
  144. // 尝试发送请求
  145. try {
  146. u = new URL(url);
  147. con = (HttpURLConnection) u.openConnection();
  148. // POST 只能为大写,严格限制,post会不识别
  149. con.setRequestMethod("POST");
  150. con.setDoOutput(true);
  151. con.setDoInput(true);
  152. con.setUseCaches(false);
  153. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  154. OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
  155. osw.write(sb.toString());
  156. osw.flush();
  157. osw.close();
  158. } catch (Exception e) {
  159. e.printStackTrace();
  160. } finally {
  161. if (con != null) {
  162. con.disconnect();
  163. }
  164. }
  165. // 读取返回内容
  166. StringBuffer buffer = new StringBuffer();
  167. try {
  168. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
  169. String temp;
  170. while ((temp = br.readLine()) != null) {
  171. buffer.append(temp);
  172. buffer.append("\n");
  173. }
  174. } catch (Exception e) {
  175. e.printStackTrace();
  176. }
  177. return buffer.toString();
  178. }
  179. }

发表评论

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

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

相关阅读

    相关 HTTP请求

    http请求分为请求头和请求体,请求头的第一行又为请求行,下面分别进行介绍。 请求头 话不多说,我们直接以一个请求头为例子来介绍,我们随便抓取一个包进行演示,下列是我抓

    相关 http请求

    http 1、是客服端与服务器传输文本的一种协议 2、http协议是无状态的 3、http协议默认端口是80 4、http协议(加密传输)端口是443