接口测试——HttpClient

article/2025/10/12 11:44:04

这里写目录标题

  • Get请求
  • Post请求
  • HttpClient设置代理
  • FastJson的应用示例
  • 常用的代码块
      • 正则表达式(提取)
      • 封装后的一个demo

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议

Get请求

  1. 一共七步,具体如下:
    (1)创建HttpClient对象
    (2)创建带请求地址的httpGet对象
    (3)执行请求,获得响应
    (4)获得响应体
    (5)获得响应内容
    (6)释放资源
    (7)断开连接
  2. 注意请求地址种有多个参数用&连接
    请求参数如果包含非英文字符,需要encode转码
    例如:String para = URLEncoder.encode("{\"pId\":\"123457\"}", "UTF-8");
  3. 想要打印响应体时,要转化为字符串。
package base;import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.testng.annotations.Test;public class GetBaidu {String URL = "http://www.baidu.com/";String url = "http://146.56.246.116:8899/common/skuList";String url3 = "http://146.56.246.116:8080/Supermarket/analysis/lookupprice?goodsCode={\"pId\":\"123457\"}";// 参数为json形式的要转化String url31 = "http://146.56.246.116:8080/Supermarket/analysis/lookupprice?goodsCode=";@Testpublic void test1() throws IOException, ParseException {String para = URLEncoder.encode("{\"pId\":\"123457\"}", "UTF-8");// 1.创建HttpClient对象CloseableHttpClient client = HttpClients.createDefault();// 2.创建带请求地址的HttpGet对象HttpGet get = new HttpGet(url31 + para);// 3.执行请求,获得响应(响应行,响应头,响应体/正文)CloseableHttpResponse response = client.execute(get);// 响应行String response_line = response.getCode() + " " + response.getReasonPhrase();System.out.println(response_line);// 响应头Header[] headers = response.getHeaders();for (Header header : headers) {System.out.println(header.getName() + header.getValue());}// 4.获得响应体HttpEntity response_entity = response.getEntity();// 5.获取响应体内容String response_str = EntityUtils.toString(response_entity, "utf-8");//转化为字符串System.out.println(response_str);// 6.释放资源EntityUtils.consume(response_entity);// 7.断开连接response.close();client.close();}}

效果如下图:
在这里插入图片描述

Post请求

  1. 步骤如下:
    (1)创建HttpClient对象
    (2)创建带请求地址的HttpPost对象
    (3)设置HttpPost对象的header属性
    (4)设置HttpPost参数(请求体)
    (5)执行HttpPost请求,获取post请求的响应
    (6)获取响应实体
    (7)获取响应内容
    (8)释放资源
    (9)断开连接

  2. 注意:
    (1)form类型、json类型请求体的创建
    (2)当请求体里又中文时,要改为utf-8编码:
    post.setEntity(new UrlEncodedFormEntity(user, Charset.forName("utf-8")));
    示例如下:

package base;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.testng.annotations.Test;public class PostDemo {@Testpublic void testForm() throws IOException, ParseException {// 1.创建httpClient对象CloseableHttpClient client1 = HttpClients.createDefault();// 2.创建一个post请求HttpPost post = new HttpPost("http://httpbin.org/post");// 3.设置请求头post.setHeader("Content-Type", "application/x-www-form-urlencoded");// 4.设置请求体// 第一种方法设置请求体List<NameValuePair> user = new ArrayList<>();user.add(new BasicNameValuePair("username", "vip"));user.add(new BasicNameValuePair("password", "secret"));// 设置POST的请求体post.setEntity(new UrlEncodedFormEntity(user));// 第二种方法设置请求体
//		HttpEntity user2 = new StringEntity("username=vip&password=secret");
//		post.setEntity(user2);// 5.执行请求CloseableHttpResponse response = client1.execute(post);// 6.获得响应实体HttpEntity entity = response.getEntity();// 7.获得响应内容String result = EntityUtils.toString(entity, "utf-8");System.out.println(result);EntityUtils.consume(entity);// 8.释放资源response.close();client1.close();}@Testpublic void testJSON() throws IOException, ParseException {// 1.创建HttpClient对象CloseableHttpClient client1 = HttpClients.createDefault();// 2.创建post请求HttpPost post = new HttpPost("http://146.56.246.116:8899/common/fgadmin/login");// 3.设置请求头post.setHeader("Content-Type", "application/json");// 4.设置请求体HttpEntity user = new StringEntity("{\"phoneArea\":\"86\", " + "  \"phoneNumber\":\"2000\"," + "  \"password\":\"123456\" }");post.setEntity(user);// 5.执行请求CloseableHttpResponse response = client1.execute(post);// 6.获得响应实体HttpEntity entity = response.getEntity();// 7.获得响应内容String result = EntityUtils.toString(entity, "utf-8");System.out.println(result);EntityUtils.consume(entity);// 7.断开连接response.close();client1.close();}}

注意

  1. 根据具体登录请求选择HttpEntity具体类型(HttpEntity的两个实现类:StringEntity和UrlEncodedEntity)
  2. 登录请求中的Content-Type需要设置正确
  3. 如果不想使用同一个HttpClient对象传递登录信息,可以考虑对需要登录信息请求分别设置cookie
    httpPost.setHeader("Cookie"," mindsparktb_232530392=true; mindsparktbsupport_232530392=true");
  4. 了解一下CookieStore

HttpClient设置代理

创建Client对象的代码改为如下,即可设置代理。(此时我们可以在fiddler中捕捉到请求和响应)

 HttpHost proxy = new HttpHost("127.0.0.1",8888);RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();CloseableHttpClient client= HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

FastJson的应用示例

FastJson是啊里巴巴的的开源库,用于对JSON格式的数据进行解析和打包。

下载jar包:
https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2
并导入eclipse

示例:

  1. 使用FastJson构建 JSON请求体
    (1)请求头的设置:post.setHeader("Content-Type", "application/json");
    (2)请求体:
JSONObject user = new JSONObject();
user.put("phoneArea", "86");
user.put("phoneNumber", "2000");
user.put("password", "123456");
  1. JSON响应的解析
JSONObject jsonResult = this.doPost(url, user);
//或者
```java
result = EntityUtils.toString(response_entity, "utf-8");
jsonResult = JSON.parseObject(result);

如获得下列响应:
在这里插入图片描述

获得各个值如下所示:

		assertEquals(jsonResult.getString("code"), "200");assertEquals(jsonResult.getString("message"), "success");
//		根据key获得json数组JSONArray array_result=jsonResult.getJSONArray("result");
//		获得json数组的第一个值JSONObject array1=array_result.getJSONObject(0);System.out.println(array1.getString("skuName"));System.out.println(array1.getIntValue("price"));System.out.println(jsonResult.containsKey("code"));System.out.println(jsonResult.get("message"));

常用的代码块

正则表达式(提取)

public static String match(String source, String left, String right) {String reg = left + "(.*?)" + right;String result = source;String s = null;Pattern pattern = Pattern.compile(reg);Matcher matcher = pattern.matcher(result);if (matcher.find()) {s = matcher.group(1);System.out.println(s);}return s;}

封装后的一个demo

package demo0909;import java.io.IOException;import java.util.List;
import java.util.Map;
import java.util.Map.Entry;import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;import com.alibaba.fastjson2.JSONObject;//课间休息至15:45
public class HttpDriver {// 返回cookiepublic static CookieStore getCookie(String url, JSONObject body) {CookieStore cookieStore = new BasicCookieStore();CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();String txt = null;HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/json");post.setEntity(new StringEntity(body.toString()));try {CloseableHttpResponse response = client.execute(post);HttpEntity entity = response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);response.close();client.close();} catch (ParseException | IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return cookieStore;}public static String doGet(String url) {CloseableHttpClient client = HttpClients.createDefault();HttpGet get = new HttpGet(url);get.setHeader("User-Agent", "PostmanRuntime/7.29.2");String txt = null;CloseableHttpResponse fee_response;try {fee_response = client.execute(get);HttpEntity entity = fee_response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);fee_response.close();client.close();} catch (ParseException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return txt;}// 将map类型的参数转化为string类型public static String mapToString(Map<String, Object> para) {StringBuilder sBuilder = new StringBuilder();sBuilder.append("?");int size = para.size();for (Entry<String, Object> entry : para.entrySet()) {sBuilder.append(entry.getKey() + "=" + entry.getValue());size--;if (size >= 1) {sBuilder.append("&");}}return sBuilder.toString();}// 返回响应体public static String doGet(String url, Map<String, Object> para) {CloseableHttpClient client = HttpClients.createDefault();HttpGet get = new HttpGet(url + mapToString(para));get.setHeader("User-Agent", "PostmanRuntime/7.29.2");String txt = null;CloseableHttpResponse fee_response;try {fee_response = client.execute(get);HttpEntity entity = fee_response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);fee_response.close();client.close();} catch (ParseException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return txt;}// 根据cookie找到对应的client对象public static String doGet(String url, CookieStore cookie) {CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookie).build();HttpGet get = new HttpGet(url);String txt = null;CloseableHttpResponse fee_response;try {fee_response = client.execute(get);HttpEntity entity = fee_response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);fee_response.close();client.close();} catch (ParseException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return txt;}//	针对的是请求体Formpublic static String doPost(String url, List<NameValuePair> body) {CloseableHttpClient client = HttpClients.createDefault();String txt = null;HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/x-www-form-urlencoded");post.setEntity(new UrlEncodedFormEntity(body));try {CloseableHttpResponse response = client.execute(post);HttpEntity entity = response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);response.close();client.close();} catch (ParseException | IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return txt;}//	针对的是请求体JSONpublic static String doPost(String url, JSONObject body) {CloseableHttpClient client = HttpClients.createDefault();String txt = null;HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/json");post.setEntity(new StringEntity(body.toString()));try {CloseableHttpResponse response = client.execute(post);HttpEntity entity = response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);response.close();client.close();} catch (ParseException | IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return txt;}public static String doPost(String url, JSONObject body, CookieStore cookieStore) {CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();String txt = null;HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/json");post.setEntity(new StringEntity(body.toString()));try {CloseableHttpResponse response = client.execute(post);HttpEntity entity = response.getEntity();txt = EntityUtils.toString(entity);EntityUtils.consume(entity);response.close();client.close();} catch (ParseException | IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return txt;}}

http://chatgpt.dhexx.cn/article/8sObLNWr.shtml

相关文章

jmeter之接口测试(http接口测试)

基础知识储备 一、了解jmeter接口测试请求接口的原理 客户端--发送一个请求动作--服务器响应--返回客户端 客户端--发送一个请求动作--jmeter代理服务器---服务器--jmeter代理服务器--服务器 二、了解基础接口知识&#xff1a; 1、什么是接口&#xff1a;前端与后台之间的…

http post请求接口测试

http post请求接口测试 单纯的http post请求&#xff0c;请求参数为json格式的接口测试总结。 方法一Postman&#xff08;推荐&#xff09;&#xff1a; 最简单的方法是用Postman &#xff08;可做post请求模拟工具用&#xff09;。真的超级简单&#xff0c;下面是操作方法&…

秒懂HTTPS接口(接口测试篇)

文章目录 一、前言二、具体实现1、引包2、采用绕过证书验证测试HTTPS接口3、采用设置信任自签名证书测试HTTPS接口4、验证数据库 三、完整项目结构 一、前言 下面我们来测试下我们秒懂HTTPS接口&#xff08;实现篇)写的HTTPS接口&#xff08;Java版&#xff09; 技术选型&…

postman进行http接口测试

无意中发现了一个巨牛的人工智能教程&#xff0c;忍不住分享一下给大家。教程不仅是零基础&#xff0c;通俗易懂&#xff0c;而且非常风趣幽默&#xff0c;像看小说一样&#xff01;觉得太牛了&#xff0c;所以分享给大家。点这里可以跳转到教程。 HTTP的接口测试工具有很多&a…

【测试】详解接口测试(2)- HTTP接口用例设计与测试方法(拿B站练手)

文章目录 前言接口测试是什么HTTP接口的测试用例设计接口用例设计小结 HTTP接口的测试方法手工测试自动化测试 接口测试策略结束语 前言 大家好&#xff0c;我是洋子。在之前的文章《详解接口测试&#xff08;1&#xff09;-常见的网络通信协议》当中&#xff0c;我们介绍了接…

接口测试入门(一)-HTTP协议基础

- 接口功能测试算是测试工程师绕不过去的一个重要技能。 - 而掌握接口测试&#xff0c;需要先知道什么是HTTP协议。 - 原理虽然很枯燥&#xff0c;但是同时也很重要。打好基础的情况下&#xff0c;才能将知识体系建的更高、更扎实 目录 一、HTTP协议基础-定义与起源 二、HTTP…

接口测试(http协议,get和post请求和响应)

TCP/IP四层协议模型 HTTP协议 超文本传输协议&#xff08;HTTP&#xff0c;HyperText Transfer Protocol)是互联网上应用最为广泛的一种网 络协议。是基于TCP/IP模型的应用层协议。 为什么叫超文本&#xff1f;不但可以传输文本数据&#xff0c;还可以传输音频、视频、超链接、…

HTTP接口测试

目录 一、什么是HTTP 1、定义 2、HTTP工作架构 3、结构&#xff08;取自菜鸟网站&#xff09; 3.1 客户端请求消息 3.2 服务端请求消息 二、如何进行HTTP接口测试 三、HTTP常用请求方式 1、GET请求 1.1 不带参数的GET请求 1.2 带参数的GET请求 2、POST请求 2.1 …

CAD图纸如何从低版本转换成高版本

我今天在绘制CAD图纸的时候突然发现&#xff0c;换个电脑后绘制好的CAD图纸打不开了。之后分析才发现是之前绘图的时候&#xff0c;保存的CAD图纸版本过低。这就需要把CAD图纸从低版本转换成高版本。今天小编就在这里给大家演示一下。 1.在电脑浏览器里搜索 xun jie CAD&#…

免费在线转换,CAD转换成PDF

为了提高我们绘图工作的效率&#xff0c;经常需要转换CAD文件的版本格式&#xff0c;例如把CAD转换成PDF格式。有没有一种不需要安装转换软件就可以快速操作方法呢&#xff1f;今天小编给大家介绍一种行之有效的方法&#xff0c;在线CAD转换器就可以帮我们快速完成这一操作。 …

cad转换器高版本转低版本怎么转?

CAD图纸由于版本过高导致无法查看和传输&#xff0c;是CAD制图工作中的小伙伴们都会遇到的问题之一。这一问题虽然不是什么大问题&#xff0c;但是也非 常影响我们正常的制图工作&#xff0c;该如何解决呢&#xff1f;今天我们就一起讨论一下&#xff0c;cad转换器高版本转低版…

cad批量转换低版本如何实现?

在CAD制图工作中&#xff0c;我们可能会遇到一些比较麻烦的问题。其中就有CAD图纸由于版本过高导致无法打开查看的问题&#xff0c;而且有时候CAD图纸过多&#xff0c;若是每 一张单独查看也会很麻烦。这时候该如何解决呢&#xff1f;cad批量转换低版本如何实现&#xff1f;今天…

怎么把高版本的CAD文件转换成低版本的

我们在打开CAD文件的时候有经常出现打不开的现象&#xff0c;这时候软件就会提示CAD版本过高&#xff0c;这时候就需要将CAD文件转换低版本了&#xff0c;那么怎么把高版本的CAD文件转换成低版本的呢&#xff1f; 这里小编就用迅捷PDF在线转换器&#xff0c;教大家CAD版本转换。…

CAD版本转换怎么操作?几个步骤教会你

CAD是建筑设计行业经常使用的图纸文件&#xff0c;但是有些图纸的格式可能会因为版本太高或者太低而打不开。不知道小伙伴们遇到这种情况是不是也束手无策呢&#xff1f;其实我们只需要使用一些软件来转换CAD版本即可。那么小伙伴们知道CAD版本转换怎么操作吗&#xff1f;还不了…

CAD版本转换怎么操作?这些方法了解了吗

目前市场上有很多CAD版本。每个人的使用习惯和计算机配置都不一样。不同版本的CAD软件生成不同的CAD文件。虽然制作CAD文件的操作方法相似&#xff0c;但新旧版本存在兼容性问题。高版本的CAD软件可以看到低版本软件制作的设计图纸&#xff0c;但低版本工具看不到高版本工具制作…

cad在线转换低版本_资源分享/CAD版本转换器

我们收集你的掌上玩物&#xff0c;我们COPY YOU。 YOU知唔知 CAD转换器 ◎消息来源&#xff1a;网络资源平台 文件预览 使用说明 1.将高版本文件拖动到转换器界面中打开 2.文件——另存问——类型选择低版本CAD格式&#xff0c;保存后的低版本文件就可以直接使用低版本CAD打…

CAD怎么转换版本?两个办法解决

CAD怎么转换版本&#xff1f;CAD文件相信建筑设计等相关行业的小伙伴都不会陌生&#xff0c;经常跟它打交道。它本身有不少版本&#xff0c;有时候同事发来的文件版本和我们的软件版本不同导致不兼容&#xff0c;这时候要进行处理就会比较麻烦&#xff0c;有没有什么方法能快速…

CAD如何免费转换PDF格式

有的时候,我们需要将我们的CAD文件转出PDF格式的文件发给客户,以便客户打开查看&#xff0c;那么我们如何将CAD文件转换为PDF格式&#xff1f;今天和大家分享一种简单的操作方法&#xff0c;并且是免费试用的。 1&#xff0c;首先打开百度首页&#xff0c;用“Speedpdf”作为关…

高版本CAD如何降低版本?来看这种降低版本方法

CAD文件的版本过高&#xff0c;我们该如何将它降低呢&#xff1f;如果有的小伙伴工作是关于CAD绘图方面的&#xff0c;就会经常使用CAD编辑软件&#xff0c;有时候在打开CAD文件时&#xff0c;会发现文件打不开&#xff0c;原因可能是文件本身受到损害&#xff0c;还有可能就是…

CAD版本怎么转换?试试这种方法

相信很多从事CAD绘图的小伙伴们对CAD版本转换应该不陌生吧&#xff0c;对于CAD版本通常有两种问题&#xff0c;一是CAD高版本可以打开低版本的图纸&#xff0c;相反低版本不能打开高版本图纸&#xff1b;二是高版本图纸转换为低版本可以直接在工具中另存为文件&#xff0c;就可…