【Java】使用 HttpURLConnection 发送 POST 和 GET 请求

古城微笑少年丶 2022-06-03 01:53 298阅读 0赞

实现代码

  1. /** * http 请求工具类 * Created by zhh on 2017/12/08. */
  2. public class HttpHelper {
  3. // 每次读取大小
  4. private final static int READ_BODY_SIZE = 5120;
  5. /** * post 方式请求内容 * @param strUrl url地址 * @param paramMap 参数集 * @return */
  6. public static String post(String strUrl, Map<String, Object> paramMap) {
  7. StringBuffer sb = new StringBuffer();
  8. for (String strKey : paramMap.keySet()) {
  9. sb.append("&");
  10. sb.append(strKey);
  11. sb.append("=");
  12. sb.append(paramMap.get(strKey));
  13. }
  14. sb.replace(0, 1, "?");
  15. if (sb.length() > 0) {
  16. return post(strUrl + sb.toString(), "");
  17. }
  18. return post(strUrl + sb.toString(), "");
  19. }
  20. /** * get 方式请求内容 * @param strUrl url地址 * @param paramMap 参数集 * @return */
  21. public static String get(String strUrl, Map<String, Object> paramMap) {
  22. StringBuffer sb = new StringBuffer();
  23. for (String strKey : paramMap.keySet()) {
  24. sb.append("&");
  25. sb.append(strKey);
  26. sb.append("=");
  27. sb.append(paramMap.get(strKey));
  28. }
  29. sb.replace(0, 1, "?");
  30. if (sb.length() > 0) {
  31. return get(strUrl + sb.toString());
  32. }
  33. return get(strUrl + sb.toString());
  34. }
  35. /** * post 方式请求内容 * @param strUrl url地址 * @param content 输出内容 * @return */
  36. public static String post(String strUrl, String content) {
  37. return post(strUrl, content, 180);
  38. }
  39. /** * get 方式请求内容 * @param strUrl url地址 * @return */
  40. public static String get(String strUrl) {
  41. return get(strUrl, 180);
  42. }
  43. /** * post 方式请求内容 * @param strUrl url地址 * @param content 输出内容 * @param timeoutSecond 设置延时时间 * @return */
  44. public static String post(String strUrl, String content, int timeoutSecond) {
  45. try {
  46. URL url = new URL(strUrl);
  47. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  48. // 连接主机超时 毫秒
  49. con.setConnectTimeout(timeoutSecond * 1000);
  50. // 从主机读取数据超时毫秒
  51. con.setReadTimeout(timeoutSecond * 1000);
  52. // 设置从HttpURLConnection读入
  53. con.setDoInput(true);
  54. // 设置是否向httpUrlConnection输出, 因为这个是post请求, 参数要放在http正文内, 因此需要设为true, 默认情况下是false
  55. con.setDoOutput(true);
  56. // 设置该URLConnection的allowUserInteraction请求头字段的值
  57. con.setAllowUserInteraction(false);
  58. con.setUseCaches(true);
  59. con.setRequestMethod("POST");
  60. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
  61. // 此处getOutputStream会隐含的进行connect,所以在开发中不调用上述的connect()也可以
  62. BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
  63. bout.write(content);
  64. bout.flush();
  65. bout.close();
  66. return streamReadHtml(con.getInputStream());
  67. } catch (MalformedURLException e) {
  68. e.printStackTrace();
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. return null;
  73. }
  74. /** * get 方式请求内容 * @param strUrl url地址 * @param timeoutSecond 设置延时时间 * @return */
  75. public static String get(String strUrl, int timeoutSecond) {
  76. try {
  77. URL url = new URL(strUrl);
  78. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  79. // 连接主机超时 毫秒
  80. con.setConnectTimeout(timeoutSecond * 1000);
  81. // 从主机读取数据超时毫秒
  82. con.setReadTimeout(timeoutSecond * 1000);
  83. con.setRequestMethod("GET");
  84. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
  85. con.connect();
  86. return streamReadHtml(con.getInputStream());
  87. } catch (MalformedURLException e) {
  88. e.printStackTrace();
  89. } catch (IOException e) {
  90. e.printStackTrace();
  91. }
  92. return null;
  93. }
  94. /** * 读取内容 * @param istream * @return * @throws UnsupportedEncodingException */
  95. public static String streamReadHtml(InputStream istream) throws UnsupportedEncodingException {
  96. String html = "";
  97. byte[] responseBody = new byte[READ_BODY_SIZE];
  98. int npos = 0;
  99. int nread = 0;
  100. try {
  101. while ((nread = istream.read(responseBody, npos, responseBody.length - npos)) >= 0) {
  102. npos += nread;
  103. byte[] tmpBuf = new byte[npos + READ_BODY_SIZE];
  104. System.arraycopy(responseBody, 0, tmpBuf, 0, npos);
  105. responseBody = tmpBuf;
  106. }
  107. } catch (IOException e) {
  108. e.printStackTrace();
  109. } finally {
  110. try {
  111. if (istream != null) {
  112. istream.close();
  113. }
  114. istream = null;
  115. } catch (Exception e) {
  116. e.printStackTrace();
  117. }
  118. }
  119. html = new String(responseBody, 0, npos, "UTF-8");
  120. return html;
  121. }
  122. }

代码用例

  1. public static void main(String[] args) {
  2. String reqUrl = "https://www.baidu.com";
  3. Map<String, Object> paramMap = new HashMap<>();
  4. paramMap.put("wd", "测试test");
  5. System.out.println(HttpHelper.post(reqUrl, paramMap));
  6. }

发表评论

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

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

相关阅读