HttpClient

HttpClient是什么

  • 是一个http通信库,支持https
  • 主要用来做网络编程,访问第三方接口

使用HttpClient

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.13version>
dependency>
public void testGet(){
    // 请求路径
    String url="xxx";

    // 创建HttpClient对象
    CloseableHttpClient client= HttpClients.createDefault();

    // 创建get请求
    HttpGet httpGet=new HttpGet(url);

    try{
        // 执行请求并且获取响应信息
        CloseableHttpResponse closeableHttpResponse= client.execute(httpGet);

        // 请求成功
        if(closeableHttpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            // 获取文档流数据
            InputStream inputStream=closeableHttpResponse.getEntity().getContent();

            // 获取json数据
            String json= EntityUtils.toString(closeableHttpResponse.getEntity());
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            client.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

public void testPost(){
    // 请求路径
    String url = "https://restapi.amap.com/v3/ip";
    
    // 创建HttpClient
    CloseableHttpClient client = HttpClients.createDefault();
    
    // 创建post请求
    HttpPost httpPost = new HttpPost(url);
    
    // 准备请求参数
    List<NameValuePair> params = new ArrayList();
    params.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));
    params.add(new BasicNameValuePair("ip", "111.201.50.56"));

    
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse res = client.execute(httpPost);
        
        // 请求成功
        if (res.getStatusLine().getStatusCode() == 200) {
            // 获取响应数据
            String json = EntityUtils.toString(res.getEntity());
            System.out.println(json);
        }
    } catch (Exception var15) {
        var15.printStackTrace();
    } finally {
        try {
            client.close();
        } catch (Exception var14) {
            var14.printStackTrace();
        }
    }
}

你可能感兴趣的:(java项目,java)