• HttpClient笔记


    一、导包

    1. <dependency>
    2. <groupId>org.apache.httpcomponentsgroupId>
    3. <artifactId>httpclientartifactId>
    4. dependency>

    二、发起请求

    (一)Get请求

    1. /**
    2. * 测试HeepClient的Get请求
    3. */
    4. @Test
    5. public void testHttpClientGet() {
    6. String api = "http://apis.juhe.cn/ip/ipNew";
    7. String ip = "112.112.11.11";
    8. // HttpClient
    9. CloseableHttpClient httpClient = HttpClients.createDefault();
    10. String url = api + "?" + "ip=" + ip + "&key=" + key;
    11. HttpGet httpGet = new HttpGet(url);
    12. try {
    13. // 发请求
    14. CloseableHttpResponse res = httpClient.execute(httpGet);
    15. String resultString = EntityUtils.toString(res.getEntity());
    16. // 一、第一种写法
    17. // Result2 result2 = JSON.parseObject(resultString, Result2.class);
    18. // log.info("result : {}", resultString);
    19. // 二、第二种写法
    20. JSONObject jsonObject = JSONObject.parseObject(resultString);
    21. if (jsonObject.getInteger("resultcode") == HttpStatus.SC_OK) {
    22. log.info("result : {}", jsonObject.get("result").toString());
    23. }
    24. } catch (IOException e) {
    25. log.info("error : {}", e.getMessage());
    26. throw new RuntimeException(e);
    27. } finally {
    28. try {
    29. httpClient.close();
    30. } catch (IOException e) {
    31. throw new RuntimeException(e);
    32. }
    33. }
    34. }

    (二)Post请求

    1. /**
    2. * 测试HeepClient的Post请求
    3. */
    4. @Test
    5. public void testHttpClientPost() {
    6. CloseableHttpClient httpClient = HttpClients.createDefault();
    7. String url = "http://apis.juhe.cn/ip/ipNew";
    8. String ip = "112.112.11.11";
    9. HttpPost httpPost = new HttpPost(url);
    10. try {
    11. // 请求体参数
    12. ArrayList nvps = new ArrayList<>();
    13. nvps.add(new BasicNameValuePair("ip", ip));
    14. nvps.add(new BasicNameValuePair("key", key));
    15. httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    16. // 发请求
    17. CloseableHttpResponse response = httpClient.execute(httpPost);
    18. String resultString = EntityUtils.toString(response.getEntity());
    19. log.info("result : {}", resultString);
    20. } catch (IOException e) {
    21. throw new RuntimeException(e);
    22. } finally {
    23. try {
    24. httpClient.close();
    25. } catch (IOException e) {
    26. throw new RuntimeException(e);
    27. }
    28. }
    29. }

  • 相关阅读:
    Pytorch中的view()函数的用法
    【C语言】指针的“最后一站”【进阶版】
    React动态添加标签组件
    Kibana生产上的常用功能总结
    照片处理软件 DxO FilmPack 7 mac中文版软件介绍
    常见排序方法原理及C语言实现
    DOM介绍及DOM获取元素的方式
    Python模板注入(SSTI)
    【高速数字化仪应用案例系列】虹科数字化仪在通信领域的应用
    MAC上使用Wireshark常见问题
  • 原文地址:https://blog.csdn.net/m0_58961367/article/details/134477361