HttpUtil.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.redxun.search.utils;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.io.*;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.Map;
  7. /**
  8. *
  9. */
  10. @Slf4j
  11. public final class HttpUtil {
  12. static final String POST = "POST";
  13. static final String GET = "GET";
  14. static final int CONN_TIMEOUT = 30000;// ms
  15. static final int READ_TIMEOUT = 30000;// ms
  16. /**
  17. * post 方式发送http请求.
  18. *
  19. * @param strUrl
  20. * @param reqData
  21. * @return
  22. */
  23. public static byte[] doPost(String strUrl,Map<String ,Object> headerMap, byte[] reqData) {
  24. return send(strUrl, POST, reqData,headerMap);
  25. }
  26. /**
  27. * get方式发送http请求.
  28. *
  29. * @param strUrl
  30. * @return
  31. */
  32. public static byte[] doGet(String strUrl) {
  33. return send(strUrl, GET, null,null);
  34. }
  35. /**
  36. * @param strUrl
  37. * @param reqmethod
  38. * @param reqData
  39. * @return
  40. */
  41. public static byte[] send(String strUrl, String reqmethod, byte[] reqData,Map<String ,Object> headerMap) {
  42. try {
  43. URL url = new URL(strUrl);
  44. HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
  45. // 携带请求头
  46. httpcon.setRequestProperty("signature",(String) headerMap.get("signature"));
  47. httpcon.setRequestProperty("businessKey",(String) headerMap.get("businessKey"));
  48. httpcon.setRequestProperty("userId",(String) headerMap.get("userId"));
  49. httpcon.setDoOutput(true);
  50. httpcon.setDoInput(true);
  51. httpcon.setUseCaches(false);
  52. httpcon.setInstanceFollowRedirects(true);
  53. httpcon.setConnectTimeout(CONN_TIMEOUT);
  54. httpcon.setReadTimeout(READ_TIMEOUT);
  55. httpcon.setRequestMethod(reqmethod);
  56. httpcon.connect();
  57. if (reqmethod.equalsIgnoreCase(POST)) {
  58. OutputStream os = httpcon.getOutputStream();
  59. os.write(reqData);
  60. os.flush();
  61. os.close();
  62. }
  63. BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"utf-8"));
  64. String inputLine;
  65. StringBuilder bankXmlBuffer = new StringBuilder();
  66. while ((inputLine = in.readLine()) != null) {
  67. bankXmlBuffer.append(inputLine);
  68. }
  69. in.close();
  70. httpcon.disconnect();
  71. return bankXmlBuffer.toString().getBytes();
  72. } catch (Exception ex) {
  73. log.error(ex.toString(), ex);
  74. return null;
  75. }
  76. }
  77. }