HTTPClient基本使用

官方网站:https://hc.apache.org/

使用maven,在xml中引用

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

第一个demo

第一个.java文件

package com.httpclient.demo;

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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

import java.io.IOException;

public class HttpClientDemo {
    @Test
    public void test01() {
        //创建get请求
        String uri = "https://www.baidu.com";
        HttpGet get = new HttpGet(uri);
        //获取http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        try {
            //由http客户端,发送get请求
            response = client.execute(get);
            //从响应中,获取响应实体
            HttpEntity respEntity = response.getEntity();
            String result = EntityUtils.toString(respEntity, "utf-8");
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 执行结果:

 将配置文件进行优化

在项目resources目录下,建一个application.properties文件,将自己需要用的常量可以放在配置文件中

在测试类中,将配置文件引入:

    @BeforeTest
    public void beforeClass() {
        //将配置文件application.properties中,加载进来
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }

字符编码:Locale.CHINA,将配置文件中的一些中文进行兼容

这个url这个变量,定义为全局变量,先在@BeforeTest中引入,然后url这个变量就被赋值了。下面就可以继续引用了

获取Cookie

下面👇这个是另一个博主写的:https://segmentfault.com/a/1190000011142669

获取响应的状态码:

           //获取响应的状态码,直接在响应response中获取
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("状态码 :" + statusCode);

 

posted @ 2019-08-20 18:04  豆芽花花儿酱  阅读(208)  评论(0编辑  收藏  举报