使用HttpClient封装的Get和Post请求

快来打我* 2023-10-11 14:38 115阅读 0赞

使用HttpClient封装的Get和Post请求,并可以将结果转为JSON对象返回

  • 导入HttpClient的依赖


    org.apache.httpcomponents
    httpclient
    4.5.2
  • 封装get和post请求

    public class HttpUtils {

  1. public static CloseableHttpClient httpClient = HttpClients.createDefault();
  2. //get
  3. public static JSONObject doGet(String url, Map<String, String> params) throws URISyntaxException, IOException {
  4. URIBuilder uriBuilder = new URIBuilder(url);
  5. if (params != null) {
  6. Set<String> keys = params.keySet();
  7. for (String key : keys) {
  8. String value = params.get(key);
  9. uriBuilder.setParameter(key,value);
  10. }
  11. }
  12. HttpGet httpGet = new HttpGet(uriBuilder.build());
  13. CloseableHttpResponse response = httpClient.execute(httpGet);
  14. System.out.println(response);
  15. return toJSONobject(response);
  16. }
  17. //post
  18. public static JSONObject doPost(String url, Map<String, String> params) throws IOException {
  19. HttpPost httpPost = new HttpPost(url);
  20. //封装post请求参数
  21. List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
  22. if (params != null){
  23. Set<String> keys = params.keySet();
  24. for (String key : keys) {
  25. String value = params.get(key);
  26. valuePairs.add(new BasicNameValuePair(key,value));
  27. }
  28. }
  29. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs,"utf8");
  30. httpPost.setEntity(formEntity);
  31. CloseableHttpResponse response = httpClient.execute(httpPost);
  32. return toJSONobject(response);
  33. }
  34. public static JSONObject toJSONobject(CloseableHttpResponse response) throws IOException {
  35. if (response.getStatusLine().getStatusCode() == 200){
  36. String json = EntityUtils.toString(response.getEntity());
  37. JSONObject jsonObject = JSON.parseObject(json);
  38. return jsonObject;
  39. }
  40. return null;
  41. }
  42. }

发表评论

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

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

相关阅读