一、导包
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
二、发起请求
(一)Get请求
public void testHttpClientGet() {
String api = "http://apis.juhe.cn/ip/ipNew";
String ip = "112.112.11.11";
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = api + "?" + "ip=" + ip + "&key=" + key;
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse res = httpClient.execute(httpGet);
String resultString = EntityUtils.toString(res.getEntity());
JSONObject jsonObject = JSONObject.parseObject(resultString);
if (jsonObject.getInteger("resultcode") == HttpStatus.SC_OK) {
log.info("result : {}", jsonObject.get("result").toString());
} catch (IOException e) {
log.info("error : {}", e.getMessage());
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
(二)Post请求
public void testHttpClientPost() {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "http://apis.juhe.cn/ip/ipNew";
String ip = "112.112.11.11";
HttpPost httpPost = new HttpPost(url);
ArrayList nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("ip", ip));
nvps.add(new BasicNameValuePair("key", key));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
String resultString = EntityUtils.toString(response.getEntity());
log.info("result : {}", resultString);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);