HttpClient与TestNG结合

1、HTTPclient插件的安装

  • 在maven项目的pom.xml中引用HTTPclient包,如下


    
        org.apache.httpcomponents
        httpclient
        4.5.6
    
  • 添加完后,maven项目会自动加载相关依赖包

2、不携带cookie的get请求


package com.course.httpclient.Demo;

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

import java.io.IOException;

public class MyHttpClient {

    @Test
    public void test1() throws IOException{

        //用来存放测试结果
        String result;
        //创建一个get实例,并指定请求url
        HttpGet get = new HttpGet("http://www.baidu.com");
        //创建一个client对象,是用来执行get方法的
        CloseableHttpClient client = HttpClients.createDefault();
        //用客户端执行get实例,并把响应结果保存在response对象中
        HttpResponse response =client.execute(get);
        //response.getEntity()用来获取整个响应的实例,即获取整个响应内容
        //EntityUtils对象是org.apache.http.util下的一个工具类,用官方的解释是为HttpEntity对象提供的静态帮助类
        //把响应内容转成字符串,转换时使用编码为utf-8
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);

    }
}

3、携带cookie的get请求


package com.course.httpclient.Cookies;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
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;
    private HttpClientContext context;
    private CloseableHttpClient client;

    @BeforeTest
    public void beforeTest(){
/*        ResourceBundle工具类,默认获取properties配置文件,因而这里只需写配置文件名即可,不需写后缀
        这里获取配置文件application,因为是在resource下,所以直接写配置文件名即可,不需加路径,
        若配置文件不在resource下,则此处需要写上相对于resource的相对路径,注:这里需要加字符编码,如中文编码Locale.CHINA*/
        //成员属性,赋值时可以拿来直接赋值,该赋值是全局性的
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        //通过工具类里的getString方法,获取配置文件里相应的键对应的值,这里获取test.url的值,获取成功时,相应配置文件里的键会变颜色,如黄色
        //这里给本类的成员属性赋值
        url = bundle.getString("test.url");
    }

    @Test
    public void testGetCookies() throws IOException {

        //用来存放测试结果
        String result;
        //从配置文件中拼接测试的url;this,表示当前对象,this.url表示引用本类的成员属性url,引用成功时,属性颜色会变化
        String uri = bundle.getString("getCookies.uri");
        String testUrl = this.url+uri;
        //创建一个get实例,并指定请求url
        HttpGet get = new HttpGet(testUrl);

        // 全局请求设置,用于获取cookie并携带cookie
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        //实例化一个cookie存储对象
        CookieStore cookieStore = new BasicCookieStore();
        // 创建HttpClient上下文
        context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        //创建一个client对象(客户端),是用来执行get方法的,获取cookie并把cookie存放在全局请求设置中,如有的话
        //静态方法,即类方法,可以不创建对象,直接引用
        client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
        //用客户端执行get实例,并把响应结果保存在response对象中,同时把cookie等信息存放在context上下文中
        HttpResponse response =client.execute(get,context);
        //response.getEntity()用来获取整个响应的实例,即获取整个响应内容
        //EntityUtils对象是org.apache.http.util下的一个工具类,用官方的解释是为HttpEntity对象提供的静态帮助类
        //把响应内容转成字符串,转换时使用编码为utf-8
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);

        //获取获取cookieStore对象中的cookies信息,并保存在对象列表中
        //List<类名> 对象名:申明一个对象列表,用来存储多个对象,其中的数据存储在相应对象的方法中
        List cookies = cookieStore.getCookies();

        //将cookie信息遍历出来,并保存在cookie对象中,即将对象列表中的对象遍历出来
        for (Cookie cookie : cookies){
            String name =cookie.getName();    //获取cookie名,通过遍历出来对象,调用相应的方法获取对象里的数据
            String value = cookie.getValue();   //获取cookie值
            System.out.println("cookie name = " + name + " ; cookie value = " + value);
        }
    }

    @Test(dependsOnMethods = {"testGetCookies"})
    public void testGetWithCookies() throws IOException {

        String result;
        String uri = bundle.getString("getdemo.withCookies");
        String testUrl = this.url+uri;
        //创建一个get实例,并指定请求url
        HttpGet get = new HttpGet(testUrl);
        //执行get请求,并带上上下文的全局设置中的cookie信息
        HttpResponse response =this.client.execute(get,this.context);

        //获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("statusCode = " + statusCode);

        if (statusCode == 200){
            //输出响应结果
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
        }
    }
}
  • 成员属性,在本类内使用,可以不加this,是全局属性;方法内定义的属性是局部的,在方法内使用;其实在方法体中引用成员变量或其他的成员方法时,引用前都隐含着“this.”,一般情况下都会缺省它,但当成员变量与方法中的局部变量同名时,为了区分且正确引用,成员变量前必须加“this.”不能缺省。

  • 在resources下的配置文件application.properties,直接给src中的类包提供需要的配置值,内容如下


application.properties


test.url=http://localhost:8866
dev.url=http://localhost:8866

getCookies.uri=/getCookies
getdemo.withCookies=/getdemo/withCookies
postdemo.withCookies=/postdemo/withCookies
login=/login

4、携带cookie的post请求


package com.course.httpclient.Cookies;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
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.Assert;
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 MyCookiesForPost {

    private String url;
    private ResourceBundle bundle;
    private HttpClientContext context;
    private CloseableHttpClient client;

    @BeforeTest
    public void beforeTest() {

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        //通过工具类里的getString方法,获取配置文件里相应的键对应的值,这里获取test.url的值,获取成功时,相应配置文件里的键会变颜色
        //这里给本类的成员属性赋值
        url = bundle.getString("test.url");
    }

    @Test
    public void testGetCookies() throws IOException {

        //用来存放测试结果
        String result;
        //从配置文件中拼接测试的url;this,表示当前对象,this.url表示引用本类的成员属性url,引用成功时,属性颜色会变化
        String uri = bundle.getString("getCookies.uri");
        String testUrl = this.url + uri;
        //创建一个get实例,并指定请求url
        HttpGet get = new HttpGet(testUrl);

        // 全局请求设置,用于获取cookie并携带cookie
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        //实例化一个cookie存储对象
        CookieStore cookieStore = new BasicCookieStore();
        // 创建HttpClient上下文
        context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
        //用客户端执行get实例,并把响应结果保存在response对象中,同时把cookie等信息存放在context上下文中
        HttpResponse response = client.execute(get, context);
        //把响应内容转成字符串,转换时使用编码为utf-8
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);

        //获取获取cookieStore对象中的cookies信息,并保存在对象列表中
        //List<类名> 对象名:申明一个对象列表,用来存储多个对象,其中的数据存储在相应对象的方法中
        List cookies = cookieStore.getCookies();

        //将cookie信息遍历出来,并保存在cookie对象中,即将对象列表中的对象遍历出来
        for (Cookie cookie : cookies) {
            String name = cookie.getName();    //获取cookie名,通过遍历出来对象,调用相应的方法获取对象里的数据
            String value = cookie.getValue();   //获取cookie值
            System.out.println("cookie name = " + name + " ; cookie value = " + value);
        }
    }

    @Test(dependsOnMethods = {"testGetCookies"})
    public void testPostMethod() throws IOException {

        String result;
        String uri = bundle.getString("postdemo.withCookies");
        String testUrl = this.url+uri;
        //创建一个post实例,并指定请求url
        HttpPost post = new HttpPost(testUrl);

        //添加参数,json格式,data格式的参数参考另一个文档
        JSONObject param = new JSONObject();
        param.put("name","huhan");
        param.put("age","18");

        //设置请求头信息,设置header
        post.setHeader("content-type","application/json");

        //将参数信息添加到方法中
        StringEntity entity = new StringEntity(param.toString(),"utf-8");

        //注入post参数数据(信息)
        post.setEntity(entity);
        //执行post请求,并带上上下文的全局设置中的cookie信息
        HttpResponse response =this.client.execute(post,this.context);

        //获取响应结果,并转成字符串
        result = EntityUtils.toString(response.getEntity(),"utf-8");

        //处理结果,判断返回结果是否符合预期
        //将返回的响应结果字符串转化成为json对象
        JSONObject resultJson = JSONObject.parseObject(result);

        //获取到结果值,并将结果强制转换成字符串
        String apiResult = (String) resultJson.get("huhan");
        String status = (String) resultJson.get("status");

        //获取响应状态码,具体断言响应结果值
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200,statusCode);
        Assert.assertEquals("success",apiResult);     //期望结果等于实际结果
        Assert.assertEquals("1",status);

    }
}

你可能感兴趣的:(HttpClient与TestNG结合)