HttpClientUtils.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.nosum.common.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.util.EntityUtils;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * 请求工具类
  13. */
  14. public class HttpClientUtils {
  15. /**
  16. * 发送get请求,利用java代码发送请求
  17. */
  18. public static String doGet(String url) {
  19. try {
  20. CloseableHttpClient httpclient = HttpClients.createDefault();
  21. HttpGet httpGet = new HttpGet(url);
  22. // 发送了一个http请求
  23. CloseableHttpResponse response = httpclient.execute(httpGet);
  24. // 如果响应200成功,解析响应结果
  25. if (response.getStatusLine().getStatusCode() == 200) {
  26. // 获取响应的内容
  27. HttpEntity responseEntity = response.getEntity();
  28. return EntityUtils.toString(responseEntity);
  29. }
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. return null;
  34. }
  35. /**
  36. * 将字符串转换成map
  37. */
  38. public static Map<String, String> getMap(String responseEntity) {
  39. Map<String, String> map = new HashMap<>();
  40. // 以&来解析字符串
  41. String[] result = responseEntity.split("\\&");
  42. for (String str : result) {
  43. // 以=来解析字符串
  44. String[] split = str.split("=");
  45. // 将字符串存入map中
  46. if (split.length == 1) {
  47. map.put(split[0], null);
  48. } else {
  49. map.put(split[0], split[1]);
  50. }
  51. }
  52. return map;
  53. }
  54. /**
  55. * 通过json获得map
  56. */
  57. public static Map<String, String> getMapByJson(String responseEntity) {
  58. Map<String, String> map = new HashMap<>();
  59. JSONObject jsonObject = JSONObject.parseObject(responseEntity);
  60. for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
  61. String key = entry.getKey();
  62. // 将obj转换成string
  63. String value = String.valueOf(entry.getValue());
  64. map.put(key, value);
  65. }
  66. return map;
  67. }
  68. }