HttpClient的使用方法

一、基本介绍:

HttpClient是模拟http客户端的一种技术。

二、使用

(这里有用到TestNG、Mock,如果不熟悉可参考本人前面博文)

1、pom文件添加依赖

<dependencies>

    <dependency>

        <groupId>org.apache.httpcomponents</groupId>

        <artifactId>httpclient</artifactId>

        <version>4.5.13</version>

    </dependency>

</dependencies>

2、httpClient的Demo

public class MyHttpClient {

    @Test

    public void test1() throws IOException {

        //用于存放结果

        String result;

        HttpGet get = new HttpGet("http://www.baidu.com");

        //用来执行get方法

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(get);

        result = EntityUtils.toString(response.getEntity(), "utf-8");

        System.out.println(result);

    }

}

3、HttpClient Get方法实现,通过mock将请求配置起来

{

  "description": "这是一个会返回cookies信息的get请求",

  "request": {

    "uri": "/getcookies",

    "method": "get"

  },

  "response": {

    "cookies": {

      "login": "true",

      "status": "10000"

    },

    "text": "恭喜获得cookies信息"

  }

}

4、配置优化方法

在resources目录下新建一个application.properties的文件,存放访问路径、uri等信息。

如:

test.url=http://localhost:8888

getCookies.uri=/getcookies

然后在java类中获取到信息

public class MyCookiesForGet {

    private String url;

    private ResourceBundle bundle;



    @BeforeTest

    public void beforeTest() {

        //自动能找到resources路径下的applica文件

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);

        url = bundle.getString("test.url");

    }



    @Test

    public void testGetCookies() throws IOException {

        String result;

        //从配置文件中拼接测试的url

        String uri = bundle.getString("getCookies.uri");

        String testUrl = this.url + uri;

        //测试代码

        HttpGet get = new HttpGet(testUrl);

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(get);

        result = EntityUtils.toString(response.getEntity(), "utf-8");

        System.out.println(result);

    }

}

5、获取cookies信息

import org.apache.http.HttpResponse;

import org.apache.http.client.CookieStore;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.cookie.Cookie;

import org.apache.http.impl.client.BasicCookieStore;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;



import java.io.IOException;

import java.util.List;

import java.util.Locale;

import java.util.ResourceBundle;



public class MyCookiesForGet {

    private String url;

    private ResourceBundle bundle;



    //用于存储cooki信息的变量

    private CookieStore store = new BasicCookieStore();



    @BeforeTest

    public void beforeTest() {

        //自动能找到resources路径下的application文件

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);

        url = bundle.getString("test.url");

    }



    /*

     *获取后端返回的response里的cookie信息

     * 后端给前端的,保持登陆信息

     */

    @Test

    public void testGetCookies() throws IOException {

        String result;

        //从配置文件中拼接测试的url

        String uri = bundle.getString("getCookies.uri");

        String testUrl = this.url + uri;

        //声明一个get请求

        HttpGet get = new HttpGet(testUrl);



        //声明一个client对象用于方法的执行,具有cookie信息

        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(store).build();



        HttpResponse response = httpClient.execute(get);

        result = EntityUtils.toString(response.getEntity(), "utf-8");

        System.out.println(result);



        //将cookies信息存到list

        //******有点问题,List长度为1,实际为2

        List<Cookie> CookieList = store.getCookies();

        System.out.println(CookieList.size());

        for (Cookie cookie : CookieList) {

            String name = cookie.getName();

            String value = cookie.getValue();

            System.out.println("name:" + name + "   value:" + value);

        }

    }

}

6、携带上面获取的cookies信息进行get请求   

 /*

     *模拟前端request携带cookie信息访问get请求,

     * 前端给后端的cookie,携带用户登录状态等,不需要数据库再去比对

     */

    @Test(dependsOnMethods = {"testGetCookies"})

    public void testGetWithCookies() throws IOException {

        String uri = bundle.getString("test.get.with.cookies");

        String testUrl = this.url + uri;

        HttpGet get = new HttpGet(testUrl);

        CloseableHttpClient httpClient =        HttpClients.custom().setDefaultCookieStore(this.store).build();

        HttpResponse response = httpClient.execute(get);

        int statusCode = response.getStatusLine().getStatusCode();

        System.out.println("statusCode = " + statusCode);

        if (statusCode == 200) {

            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            System.out.println(result);

        }

    }

7、携带cookies、header、参数的post请求

public class MyCookiesForPost {

    private String url;

    private ResourceBundle bundle;

    @BeforeTest

    public void beforeTest() {

        //自动能找到resources路径下的application文件

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);

        url = bundle.getString("test.url");

    }

    @Test

    public void testPostMethod() throws IOException {

        String uri = bundle.getString("test.post.with.cookies");

        String testUrl = this.url + uri;

        //设置cookies信息

        CookieStore store = new BasicCookieStore();

        BasicClientCookie testCookie = new BasicClientCookie("login","true");

        testCookie.setDomain("localhost");

        testCookie.setPath("/");

        store.addCookie(testCookie);

        //声明一个client对象,用来进行方法的执行

        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(store).build();

        //声明一个方法,这个方法就是post方法

        HttpPost post = new HttpPost(testUrl);

        //添加参数

        JSONObject param = new JSONObject();

        param.put("name", "zhangsan");

        param.put("age", "18");

        //设置请求信息 设置header

        post.setHeader("content-type", "application/json");

        //将参数信息添加到方法中

        StringEntity entity = new StringEntity(param.toString(), "utf-8");

        post.setEntity(entity);

        //声明一个对象来进行响应结果的存储

        String result;

        //执行post方法

        HttpResponse response = httpClient.execute(post);

        //获取响应结果

        result = EntityUtils.toString(response.getEntity(), "utf-8");

        System.out.println(result);

        //处理结果,就是判断返回结果是否符合预期

        //将返回的相应的结果字符串转换为json对象

        JSONObject resultJson = new JSONObject(result);

        //具体的判断返回的结果的值

        //获取到结果值,assertEquals(实际结果,预期结果)

        String zhangsan = (String) resultJson.get("zhangsan");

        String status = (String) resultJson.get("status");

        Assert.assertEquals("success", zhangsan);

        Assert.assertEquals("1", status);

    }

}

总结流程:

//声明一个get或post请求

HttpPost post = new HttpPost(url);

HttpGet get = new HttpGet(url);

//声明一个client对象,用于方法的执行

CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(store).build;

//设置请求信息 设置header

post.setHeader("content-type", "application/json");

//添加json格式参数

JSONObject param = new JSONObject();

param.put("name", "zhangsan");

param.put("age", "18");

//将参数信息添加到方法中

StringEntity entity = new StringEntity(param.toString(), "utf-8");

post.setEntity(entity);

//执行post或get请求

HttpResponse response = httpclient.execute(post);

HttpResponse response = httpclient.execute(get);

//用于存放结果

String result;

//获取响应结果

result = EntityUtils.toString(response.getEntity(),”utf-8”);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值