汕頭網(wǎng)站推廣教程2345瀏覽器網(wǎng)址導航
一、介紹
HttpClient是Apache?Jakarta?Common?下的子項目,可以用來提供高效的、最新的、功能豐富的支持?HTTP?協(xié)議的客戶端編程工具包。?
HttpClient?是一個HTTP通信庫、一個工具包,它只提供一個通用瀏覽器應用程序所期望的功能子集,與瀏覽器相比是沒有界面的。
二、添加依賴
<!--httpclient--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.14</version></dependency>
二、測試
我們先創(chuàng)建一個用于測試的實體類
package com.example.fastjsondemo.model;import lombok.Data;/*** @author qx* @date 2023/8/29* @des 測試的實體類*/
@Data
public class Map {private String status;private String info;private String infocode;private String province;private String city;private String adcode;private String rectangle;
}
測試Get請求
/*** 測試get請求*/@Testvoid testGet() throws IOException {String url = "https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip=171.110.83.78";CloseableHttpClient client = HttpClients.createDefault();HttpGet httpGet = new HttpGet(url);CloseableHttpResponse response = client.execute(httpGet);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String json = EntityUtils.toString(response.getEntity());Map map = JSONObject.parseObject(json, Map.class);System.out.println(map);}}
執(zhí)行Get請求輸出:
Map(status=1, info=OK, infocode=10000, province=廣西壯族自治區(qū), city=梧州市, adcode=450400, rectangle=111.1604726,23.41005092;111.4408064,23.57943575)
測試Post請求
/*** 測試Post請求** @throws IOException*/@Testvoid testPost() throws IOException {CloseableHttpClient client = HttpClients.createDefault();String url = "https://restapi.amap.com/v3/ip";HttpPost httpPost = new HttpPost(url);// 參數(shù)設置List<NameValuePair> paramList = new ArrayList<>();paramList.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));paramList.add(new BasicNameValuePair("ip", "171.110.83.78"));// 設置httpPost使用的參數(shù)httpPost.setEntity(new UrlEncodedFormEntity(paramList));// 執(zhí)行CloseableHttpResponse response = client.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String json = EntityUtils.toString(response.getEntity());Map map = JSONObject.parseObject(json, Map.class);System.out.println(map);}}
執(zhí)行Post請求輸出
Map(status=1, info=OK, infocode=10000, province=廣西壯族自治區(qū), city=梧州市, adcode=450400, rectangle=111.1604726,23.41005092;111.4408064,23.57943575)