1、HTTPclient插件的安装

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

<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
  • 添加完后,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<Cookie> 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<Cookie> 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结合的更多相关文章

  1. Java + maven + httpclient + testng + poi实现接口自动化

    一.maven中引入httpclient.testng.poi依赖包 <project xmlns="http://maven.apache.org/POM/4.0.0" x ...

  2. 做自动化测试选择Python还是Java?

    你好,我是测试蔡坨坨. 今天,我们来聊一聊测试人员想要进阶,想要做自动化测试,甚至测试开发,如何选择编程语言. 前言 自动化测试,这几年行业内的热词,也是测试人员进阶的必备技能,更是软件测试未来发展的 ...

  3. 接口自动化:HttpClient + TestNG + Java(四) - 封装和测试post方法请求

    在上一篇中,我们对第一个自动化接口测试用例做了初步优化和断言,这一篇我们处理POST请求. 4.1 发送POST方法请求 post方法和get方法是我们在做接口测试时,绝大部分场景下要应对的主要方法. ...

  4. 接口自动化:HttpClient + TestNG + Java(三) - 初步封装和testng断言

    在上一篇中,我们写了第一个get请求的测试类,这一篇我们来对他进行初步优化和封装 3.1 分离请求发送类 首先想到的问题是,以后我们的接口自动化测试框架会大量用到发送http请求的功能. 那么这一部分 ...

  5. 接口自动化:HttpClient + TestNG + Java(二) - 第一个接口测试:get请求

    在上一篇中,我们搭建好了HttpClient + TestNG + Java的自动化接口测试环境,这一篇我们就赶紧开始编写我们的第一个接口测试用例. 本篇会对问题解决的思路进行更详尽的阐述. 2.1 ...

  6. 接口自动化:HttpClient + TestNG + Java(一) - 接口测试概述+自动化环境搭建

    1.1 接口测试简介 1.1.1 什么是接口测试 开始学习接口自动化测试之前,我们先要来了解什么是接口,以及什么是接口测试. 我们都知道,测试从级别上划分可以分为 组件测试 集成测试 系统测试 验收测 ...

  7. HttpClient + Testng实现接口测试

    HttpClient教程 : https://www.yeetrack.com/?p=779 一,所需要的环境: 1,testng .httpclient和相关的依赖包 二.使用HttpClient登 ...

  8. 接口测试 java+httpclient+testng+excel

    最近项目不忙,研究了下java实现接口自动化,借助testng+excel实现数据驱动 目前只用post方式测试,返回结果列没有通过列名去找 另外,请求参数是转义之后的,接口之间的依赖也是个问题,批量 ...

  9. 基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport的接口自动化测试框架

    接口自动化框架 项目说明 本框架是一套基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport而设计的数据驱动接口自动化测试框架,TestNG ...

随机推荐

  1. vue 报错碰到的一些问题及其规范

    报错信息:Expected error to be handled(需要处理的错误) 这是因为回调函数里面的参数error没有运用到,所以可以不设置参数,或者在回调函数内console.log(err ...

  2. 使用node搭建静态资源服务器

    安装 npm install yumu-static-server -g 使用 shift+鼠标右键  在此处打开Powershell 窗口 server # 会在当前目录下启动一个静态资源服务器,默 ...

  3. opencv3.2.0+opencv_contrib-3.2.0+vs2015开发配置

    在sift算法实现中,出现了这个问题 出现问题:\vs2015opencv\vs2015\project\mode\mode\sift算法1.cpp(3): fatal error C1083: 无法 ...

  4. jdk8-》allMatch、anyMatch、max、min函数

    allMatch函数: 检查是否匹配所有元素,只有全部符合才返回true boolean flag = list.stream().allMatch(obj->obj.length()>5 ...

  5. C++-POJ2234-Matches Game[Nim][SG函数]

    #include <set> #include <map> #include <cmath> #include <queue> #include < ...

  6. Python调用libsvm

    # -*- coding: utf-8 -*- import os, sys path = r"D:\Program Files (x86)\libsvm-3.22\python" ...

  7. Apache 安装概要

    1.apache下载参照百度 bin文件夹下命令行:  httpd -k install 2.安装完成后排错记录 服务无法启动,到bin目录下运行  httpd.exe  查看输出,然后百度一下输出即 ...

  8. Laravel 中使用 Laravel-Excel 美化

    <?php use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; use Maatwebsite\Excel\Exceptions\Larav ...

  9. 初识Vue--生命周期

    初学Vue,写一些随记谨防忘记,不足之处谢谢指出!!! 本文可以直接复制自行创建一个HTML页面,查看结果. <!DOCTYPE html> <html lang="en& ...

  10. Apache Kafka(四)- 使用 Java 访问 Kafka

    1. Produer 1.1. 基本 Producer 首先使用 maven 构建相关依赖,这里我们服务器kafka 版本为 2.12-2.3.0,pom.xml 文件为: <?xml vers ...