httpClient 配置与测试

Posted asplover

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:测试配置成功源码

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);

        }
    }
}

 

以上是关于httpClient 配置与测试的主要内容,如果未能解决你的问题,请参考以下文章

接口测试教程-jmeter

Jmeter介绍

(转)HttpURLConnection与 HttpClient 区别

接口-httpClient

HttpClient“任务被取消”

接口测试HttpClient&fastJson 总结与案例