• 接口测试——HttpClient


    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=";
    
    	@Test
    	public 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 {
    
    	@Test
    	public 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();
    	}
    
    	@Test
    	public 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 {
    
    	// 返回cookie
    	public 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 block
    			e1.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 block
    			e.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 block
    			e.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 block
    			e.printStackTrace();
    		}
    		return txt;
    
    	}
    
    //	针对的是请求体Form
    	public 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 block
    			e1.printStackTrace();
    		}
    		return txt;
    
    	}
    
    //	针对的是请求体JSON
    	public 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 block
    			e1.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 block
    			e1.printStackTrace();
    		}
    		return txt;
    
    	}
    
    }
    
    
  • 相关阅读:
    jenkins+git持续集成配置
    05高级变量
    使用 AI 学习 Python web 的 django 代码(1/30天)
    深入理解二叉树:结构、遍历和实现
    npm是如何处理多版本依赖的?
    io概述及其分类
    北斗导航 | BDS RTK高精度定位算法在形变检测中的应用(算法原理讲解)
    2023 山东省赛 【9.28训练补题】
    两个线程交替打印A1B2C3D4E5输出,6种实现方式
    移动端适配解决方案
  • 原文地址:https://blog.csdn.net/m0_51508220/article/details/126863880