HttpUtil.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.ruoyi.common.utils;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * http 工具类
  11. */
  12. public class HttpUtil {
  13. public static String post(String requestUrl, String accessToken, String params)
  14. throws Exception {
  15. String contentType = "application/x-www-form-urlencoded";
  16. return HttpUtil.post(requestUrl, accessToken, contentType, params);
  17. }
  18. public static String post(String requestUrl, String accessToken, String contentType, String params)
  19. throws Exception {
  20. String encoding = "UTF-8";
  21. if (requestUrl.contains("nlp")) {
  22. encoding = "GBK";
  23. }
  24. return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
  25. }
  26. public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
  27. throws Exception {
  28. String url = requestUrl + "?access_token=" + accessToken;
  29. return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
  30. }
  31. public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
  32. throws Exception {
  33. URL url = new URL(generalUrl);
  34. // 打开和URL之间的连接
  35. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  36. connection.setRequestMethod("POST");
  37. // 设置通用的请求属性
  38. connection.setRequestProperty("Content-Type", contentType);
  39. connection.setRequestProperty("Connection", "Keep-Alive");
  40. connection.setUseCaches(false);
  41. connection.setDoOutput(true);
  42. connection.setDoInput(true);
  43. // 得到请求的输出流对象
  44. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  45. out.write(params.getBytes(encoding));
  46. out.flush();
  47. out.close();
  48. // 建立实际的连接
  49. connection.connect();
  50. // 获取所有响应头字段
  51. Map<String, List<String>> headers = connection.getHeaderFields();
  52. // 遍历所有的响应头字段
  53. for (String key : headers.keySet()) {
  54. System.err.println(key + "--->" + headers.get(key));
  55. }
  56. // 定义 BufferedReader输入流来读取URL的响应
  57. BufferedReader in = null;
  58. in = new BufferedReader(
  59. new InputStreamReader(connection.getInputStream(), encoding));
  60. String result = "";
  61. String getLine;
  62. while ((getLine = in.readLine()) != null) {
  63. result += getLine;
  64. }
  65. in.close();
  66. System.err.println("result:" + result);
  67. return result;
  68. }
  69. }