HttpClient笔记

一、导包


    org.apache.httpcomponents
    httpclient

二、发起请求

(一)Get请求

/**
 * 测试HeepClient的Get请求
 */
@Test
public void testHttpClientGet() {
    String api = "http://apis.juhe.cn/ip/ipNew";
    String ip = "112.112.11.11";
    // HttpClient
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String url = api + "?" + "ip=" + ip + "&key=" + key;
    HttpGet httpGet = new HttpGet(url);
    try {
        // 发请求
        CloseableHttpResponse res = httpClient.execute(httpGet);
        String resultString = EntityUtils.toString(res.getEntity());
        // 一、第一种写法
//            Result2 result2 = JSON.parseObject(resultString, Result2.class);
//            log.info("result : {}", resultString);
        // 二、第二种写法
        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);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

(二)Post请求

/**
 * 测试HeepClient的Post请求
 */
@Test
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);
    try {
        // 请求体参数
        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);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

你可能感兴趣的:(中间件,Java,中间件,HttpClient)