HttpClient

发布时间:2023年12月19日

Apache官方文档:https://hc.apache.org/httpcomponents-client-5.2.x/
依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

GET 和 POST 请求

public static void main(String[] args) {
    // 创建客户端对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建GET请求对象
    HttpGet httpGet = new HttpGet("https://restapi.amap.com/");
    // 创建POST请求对象
    HttpPost httpPost = new HttpPost("https://restapi.amap.com/v3/ip");
    // 创建请求参数
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("ip","0.0.0.0"));
    try {
        // 设置POST请求参数
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        // 发送GET请求,返回响应对象
        CloseableHttpResponse getResponse = httpClient.execute(httpGet);
        // 发送POST请求,返回响应对象
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);
        // 判断响应状态码
        if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            // GET请求成功,读取响应数据
            System.out.println(EntityUtils.toString(getResponse.getEntity()));
        }
        if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            // POST请求成功,读取响应数据
            System.out.println(EntityUtils.toString(postResponse.getEntity()));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            // 关闭客户端
            httpClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
文章来源:https://blog.csdn.net/h_e_l_l_o_______/article/details/135072743
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。