HttpClient简介与进行测试get/post请求(带cookie)

1 HttpClient

HttpClient 提供的主要的功能

  • 实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等

2 使用mock来创建用来测试的接口

startupWithCookies.json文件里面创建一个会返回cookies的get请求、一个带有cookies才能访问的get请求与带有cookies的post请求,接下来

[
  {
    "description":"这是一个会返回cookies信息的get请求",
    "request":{
      "uri":"/getCookies",
      "method":"get"
    },
    "response":{
      "cookies":{
        "login":"true"
      },
      "text":"恭喜你获得cookies信息成功",
      "headers":{
        "Content-Type":"text/html;charset=gbk"
      }
    }


  },


  {
    "description":"这是一个带cookies信息的get请求",
    "request":{
      "uri":"/get/with/cookies",
      "method":"get",
      "cookies":{
        "login":"true"
      }
    },
    "response":{
      "text":"这是一个需要携带cookies信息才能访问的get请求",
      "headers":{
        "Content-Type":"text/html;charset=gbk"
      }
    }
  },
  {
    "description":"这是一个带cookies信息的post请求",
    "request":{
      "uri":"/post/with/cookies",
      "method":"post",
      "cookies":{
        "login":"true"
      },
      "json":{
        "name":"huhansan",
        "age":"18"
      }
    },
    "response":{
      "status":200,
      "json":{
        "huhansan":"success",
        "status":"1"
      },
      "headers":{
        "Content-Type":"text/html;charset=gbk"
      }
    }
  }

]

将编写的接口等运行起来,运行起来后后续才可以进行测试
在这里插入图片描述

3 使用httpclient测试会返回cookies的get请求

即是这一个接口:
即当访问http://localhost:8899/getCookies时会返回login:true的cookies值

 {
    "description":"这是一个会返回cookies信息的get请求",
    "request":{
      "uri":"/getCookies",
      "method":"get"
    },
    "response":{
      "cookies":{
        "login":"true"
      },
      "text":"恭喜你获得cookies信息成功",
      "headers":{
        "Content-Type":"text/html;charset=gbk"
      }
    }
  }

appliction.properties文件里面存放的是一些待测试的接口

test.url = http://localhost:8899
dev.url = http://localhost:8899
getCookies.uri =/getCookies
test.get.with.cookies = /get/with/cookies
test.post.with.cookies = /post/with/cookies
login = /login

在使用httpclient框架时需要导入的依赖,即pom.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.course.code</groupId>
    <artifactId>Chapter9</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.1.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
    </dependencies>
</project>

使用HttpClient来测试会返回cookies的get请求

package com.course.httpclient.cookie;

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.DefaultHttpClient;
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 MyCookieForGet {
   private String url;
    private ResourceBundle bundle;
    //用来存储cookies信息的变量
    private CookieStore store;
    @BeforeTest
    public void beforeTest(){
        //来获取application文件的里面的测试url,要使用bundle才能获取
        bundle = ResourceBundle.getBundle("appliction", 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);
//      new 一个 client对象用来执行get请求的
        DefaultHttpClient client = new DefaultHttpClient();
        // 执行get请求,并使用response来存放执行后返回的响应内容
        HttpResponse response = client.execute(get);
        //使用result来存放响应后内容,主要要使用utf-8
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

        //获取cookies信息
        this.store = client.getCookieStore();
        //因为cookie里面的内容是使用key:value的格式进行存放的,使用list进行存放cookie内容
        List<Cookie> cookieList = store.getCookies();
// 读取cookie中内容
        for (Cookie cookie : cookieList){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name = " + name
            + ";  cookie value = " + value);
        }

    }

    @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);
        DefaultHttpClient client = new DefaultHttpClient();

        //设置cookies信息
        client.setCookieStore(this.store);

        HttpResponse response = client.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);
        }
    }
}

运行结果:
在这里插入图片描述

4 使用httpclient测试一个带cookie的post请求

即是测试一个携带login:true的cookie信息的post请求

{
    "description":"这是一个带cookies信息的post请求",
    "request":{
      "uri":"/post/with/cookies",
      "method":"post",
      "cookies":{
        "login":"true"
      },
      "json":{
        "name":"huhansan",
        "age":"18"
      }
    },
    "response":{
      "status":200,
      "json":{
        "huhansan":"success",
        "status":"1"
      },
      "headers":{
        "Content-Type":"text/html;charset=gbk"
      }
    }
  }

使用HttpClient来测试带cookies的post请求,
在测试代码中,我是先利用上面的会返回cookie的get请求来获取cookie,在将cookie作为post需要携带的cookie内容。

package com.course.httpclient.cookie;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
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 MyCookieForPost {
    private String url;
    private ResourceBundle bundle;
    //用来存储cookies信息的变量
    private CookieStore store;
    @BeforeTest
    public void beforeTest(){
        bundle = ResourceBundle.getBundle("appliction", 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);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

        //获取cookies信息
        this.store = client.getCookieStore();
        List<Cookie> cookieList = store.getCookies();

        for (Cookie cookie : cookieList){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name = " + name
                    + ";  cookie value = " + value);
        }

    }

    @Test(dependsOnMethods = {"testGetCookies"})
    public void testPostMethod() throws IOException {
        String uri = bundle.getString("test.post.with.cookies");
        //拼接最终的测试地址
        String testUrl = this.url + uri;

        //声明一个Client对象,用来进行方法的执行
        DefaultHttpClient client = new DefaultHttpClient();

        //声明一个方法,这个方法就是post方法
        HttpPost post = new HttpPost(testUrl);

        //添加参数
        JSONObject param = new JSONObject();
        param.put("name","huhansan");
        param.put("age","18");

        //设置请求头信息 设置header
        post.setHeader("content-type","application/json");
        //将参数信息添加到方法中
        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);
        //声明一个对象来进行响应结果的存储
        String result;
        //设置cookies信息
        client.setCookieStore(this.store);
        //执行post方法
        HttpResponse response = client.execute(post);
        //获取响应结果
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        //处理结果,就是判断返回结果是否符合预期
        //将返回的响应结果字符串转化成为json对象
        JSONObject resultJson = new JSONObject(result);


        //获取到结果值
        String success = (String) resultJson.get("huhansan");
        String status = (String) resultJson.get("status");
        //具体的判断返回结果的值
        Assert.assertEquals("success",success);
        Assert.assertEquals("1",status);

    }
}

运行结果:
在这里插入图片描述
这是我学习慕课《面面俱到的java接口自动化测试实战》里面的httpclient框架部分的内容,上述的代码对应第九章的内容,觉得有用可以到我的github上下载运行。
https://github.com/hhhhhhe/Interface_Auto_Test

©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页