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. 检测识别问题中的metrics

    之前一直记不熟各种指标的具体计算,本文准备彻底搞定这个问题,涵盖目前遇到过的所有评价指标. TP,TN,FP,FN 首先是true-false和positive-negative这两对词.以二分类为例 ...

  2. SIFT算法原理(3)-确定关键点的主方位,构建关键点描述符

    介绍官网:https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_sift_intro/py_sift_intro.html ...

  3. DE1_MSEL

    基础的一般实验:01001(现在用的)或10010 马上换linux,做个记录: sd卡启动linux系统时,启动开关0至4位拨至00000

  4. centos软连接的增删

    软连接操作 增加 ln-s 源文件 软连接名 修改 ln –snf 源文件 软连接 删除 只删除软连接 rm -rf 软连接名 只删除源文件 rm -rf 源文件 -r循环 -f强制

  5. asp.net mvc获取http body中的json

    今天遇到一个对方直接post 一共json对象字符串过来的场景.按照以前的旧方案方法可以直接在request.inputstream里面读取,然后反序列化即可.(当然估计ASP.NET MVC应该有更 ...

  6. python&selenium自动化测试实战项目

    https://www.cnblogs.com/linuxchao/p/linuxchao-python-selenium-demo.html

  7. Xshell5配置ssh免密码登录-公钥与私钥登录linux服务器(xshell如何登陆上阿里云服务器)

    原文地址:https://blog.csdn.net/longgeaisisi/article/details/78680180 ssh登录提供两种认证方式:口令(密码)认证方式和密钥认证方式.其中口 ...

  8. D0 设计模式

    单一职责 一个类只负责一个功能领域中的相应职责.,就一个类而言,应该只有一个引起它变化的原因. 单一职责原则告诉我们: 一个类不能太"累"! 在软件系统中, 一个类( 大到模块, ...

  9. python hashlib 详解

    1.概述 摘要算法简介 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...

  10. 《软件测试52讲》读书笔记 —— API测试怎么做

    前言 文章中还介绍了测试工具,比如cURL.postman,单API如何测试:但这些都是偏基础的东西,且网上教程各式各样,就不再赘述了:这里主要讲的就是关于复杂场景的API测试要如何应对 API测试的 ...