HttpServiceUtils.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.xynet.marketing.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import java.util.Map;
  9. /**
  10. * @author YanJ
  11. * @date 2020/1/9-10:55
  12. */
  13. public class HttpServiceUtils {
  14. public static String sendPost(String urlParam, Map<String, String> params, String charset) {
  15. StringBuffer resultBuffer = null;
  16. // 构建请求参数
  17. StringBuffer sbParams = new StringBuffer();
  18. if (params != null && params.size() > 0) {
  19. for (Map.Entry<String, String> e : params.entrySet()) {
  20. sbParams.append(e.getKey());
  21. sbParams.append("=");
  22. sbParams.append(e.getValue());
  23. sbParams.append("&");
  24. }
  25. }
  26. URLConnection con = null;
  27. OutputStreamWriter osw = null;
  28. BufferedReader br = null;
  29. try {
  30. URL realUrl = new URL(urlParam);
  31. // 打开和URL之间的连接
  32. con = realUrl.openConnection();
  33. // 设置通用的请求属性
  34. con.setRequestProperty("accept", "*/*");
  35. con.setRequestProperty("connection", "Keep-Alive");
  36. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  37. con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  38. // 发送POST请求必须设置如下两行
  39. con.setDoOutput(true);
  40. con.setDoInput(true);
  41. // 获取URLConnection对象对应的输出流
  42. osw = new OutputStreamWriter(con.getOutputStream(), charset);
  43. if (sbParams != null && sbParams.length() > 0) {
  44. // 发送请求参数
  45. osw.write(sbParams.substring(0, sbParams.length() - 1));
  46. // flush输出流的缓冲
  47. osw.flush();
  48. }
  49. // 定义BufferedReader输入流来读取URL的响应
  50. resultBuffer = new StringBuffer();
  51. int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
  52. if (contentLength > 0) {
  53. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  54. String temp;
  55. while ((temp = br.readLine()) != null) {
  56. resultBuffer.append(temp);
  57. }
  58. }
  59. } catch (Exception e) {
  60. throw new RuntimeException(e);
  61. } finally {
  62. if (osw != null) {
  63. try {
  64. osw.close();
  65. } catch (IOException e) {
  66. osw = null;
  67. throw new RuntimeException(e);
  68. }
  69. }
  70. if (br != null) {
  71. try {
  72. br.close();
  73. } catch (IOException e) {
  74. br = null;
  75. throw new RuntimeException(e);
  76. }
  77. }
  78. }
  79. return resultBuffer.toString();
  80. }
  81. }