httpClient 配置与测试

1:pom.xml 输入依赖jar坐标

 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.6</version>
    </dependency>
  </dependencies>

2:测试配置成功源码
  httpClient编写流程
a)创建httpClient
b)创建请求方式如httpGet,同时设置网址
c)httpClient.执行请求,并返回对象, CloseableHttpResponse response = httpClient.execute(httpGet);
d)通过CloseableHttpResponse 对象得到相应数据(如.getEntiny())

package com.ibaiqi.gather.httpClientStudy;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.net.www.http.HttpClient;

import java.io.IOException;

/**
 * @version 1.0.0
 * @program: recuit_gather
 * @description:
 * @author: zhangdaxu
 * @create: 2020-03-13 10:47
 */
public class httpClientStu01 {
    public static void main(String[] args) throws IOException {
        System.out.println("测试httpClient配置");
        //1:创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2:通过httpGet发起get方式,传入网址为参数,并创建httpGet对象。
        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        //3:使用httpClient对象发起请求,
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println(response);
        //4:解析响应,从页获取数据
        //判断http状态码
        if(response.getStatusLine().getStatusCode()==200){
            //Entity是发送和接收信息载体、 httpEntity可能通过request或 reponse
            HttpEntity httpEntity = response.getEntity();
            System.out.println("输出httpEntity对象");
            System.out.println(httpEntity);
            //不加UTF-8参数,会中文乱码
            String content = EntityUtils.toString(httpEntity,"UTF-8");
            System.out.println("获取内容"+content);

        }
    }
}
做产品的程序,才是好的程序员!
原文地址:https://www.cnblogs.com/asplover/p/12485483.html