java接口自动化系列(09):发送http请求
本系列汇总,请查看这里:https://www.cnblogs.com/uncleyong/p/15867903.html
实现目标
发送http请求,获取服务器响应。
关于被测试接口
配套练习环境(含相关接口):https://www.cnblogs.com/uncleyong/p/17165143.html
添加pom依赖
发送http请求的依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
创建配置文件
config.properties(被测试项目的ip、端口)
project.ip = 192.168.117.180 project.port = 18089
拼接ip、端口、url
测试类BaseCase中添加属性和静态代码快
public static Properties properties = new Properties(); static { try { // 解决properties中中文乱码 InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("src\\test\\resources\\config.properties"), "GBK"); properties.load(inputStreamReader); } catch (IOException e) { e.printStackTrace(); } }
测试方法中添加拼接url的逻辑
// 拼接url url = "http://" + properties.getProperty("project.ip").trim() + ":"+ properties.getProperty("project.port").trim() + url; logger.info(url);
添加工具类
发送json:HttpRequestJsonUtil.java
package com.qzcsbj.autotest.utils; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.Set; /** * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <json方式:post请求> */ public class HttpRequestJsonUtil { // 声明为静态方法,方便调用 public static String postRequest(String url, JSONObject jsonObject, JSONObject headers){ String res = ""; HttpPost httpPost = new HttpPost(url); // 通过形参设置请求头 Set<String> headerkeys = headers.keySet(); for (String headerkey : headerkeys) { httpPost.addHeader(headerkey.trim(),headers.getString(headerkey).trim()); } // 发送 json 类型数据 httpPost.setEntity(new StringEntity(jsonObject.toString(),"UTF-8")); // 创建可供关闭的发包客户端 CloseableHttpClient httpClient = HttpClients.createDefault(); // 发送请求 HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpPost); // System.out.println("状态码:" + httpResponse.getStatusLine().getStatusCode()); res = EntityUtils.toString(httpResponse.getEntity()); // res = EntityUtils.toString(httpResponse.getEntity(),"UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return res; } public static String sendRequest(String url, String requestType, JSONObject jsonObject, JSONObject headers){ String response = ""; if ("post".equalsIgnoreCase(requestType)){ response = postRequest(url, jsonObject, headers); }else { response = "error request type!!!"; } return response; } }
发送非json:HttpRequestUtil.java
package com.qzcsbj.autotest.utils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <k-v方式:get、post请求> */ public class HttpRequestUtil { // 声明为静态方法,方便调用 public static String getRequest(String url, Map<String,String> params){ String res = ""; boolean flag = true; Set<String> keys = params.keySet(); for (String key : keys) { // 第一个参数用?连接,后面的用&连接 if (flag){ url += "?" + key + "=" + params.get(key); flag = false; }else { url += "&" + key + "=" + params.get(key); } } // System.out.println(url); HttpGet httpGet = new HttpGet(url); HttpClient httpClient = HttpClients.createDefault(); try { HttpResponse response = httpClient.execute(httpGet); res = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } finally { try { ((CloseableHttpClient) httpClient).close(); } catch (IOException e) { e.printStackTrace(); } } return res; } // 声明为静态方法,方便调用 public static String postRequest(String url, Map<String,String> params){ String res = ""; HttpPost httpPost = new HttpPost(url); ArrayList<BasicNameValuePair> basicNameValuePairs = new ArrayList<BasicNameValuePair>(); // 上面可以写为: // List<NameValuePair> basicNameValuePairs = new ArrayList<NameValuePair>(); // 遍历map,放到basicNameValuePairs中 Set<String> keys = params.keySet(); for (String key : keys) { basicNameValuePairs.add(new BasicNameValuePair(key,params.get(key))); } HttpClient httpClient = HttpClients.createDefault(); try { // 将Content-Type设置为application/x-www-form-urlencoded类型 httpPost.setEntity(new UrlEncodedFormEntity(basicNameValuePairs,"utf-8")); HttpResponse httpResponse = httpClient.execute(httpPost); res = EntityUtils.toString(httpResponse.getEntity()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ((CloseableHttpClient) httpClient).close(); } catch (IOException e) { e.printStackTrace(); } } return res; } public static String sendRequest(String url, String requestType, Map<String, String> parameters){ String response = ""; if ("get".equalsIgnoreCase(requestType)){ response = getRequest(url, parameters); }else if ("post".equalsIgnoreCase(requestType)){ response = postRequest(url, parameters); }else { response = "error request type!!!"; } return response; } }
发送http请求
测试方法中添加以下逻辑
String actual = null; JSONObject headsJsonObject = JSONObject.parseObject(headers); // 根据请求头判断是发送json还是非json if (headsJsonObject!=null && "application/json".equals(headsJsonObject.getString("Content-Type"))){ // 解析json格式字符串为JSONObject JSONObject paramJsonObject = JSONObject.parseObject(parameters); // 请求 actual = HttpRequestJsonUtil.sendRequest(url, requestType, paramJsonObject,headsJsonObject); logger.info("json请求返回结果: " + actual); } else { HashMap<String, String> params = new HashMap<String, String>(); // 解析json格式字符串为JSONObject JSONObject jsonObject = JSONObject.parseObject(parameters); // JSONObject转换为map Set<String> keys = jsonObject.keySet(); for (String key : keys) { params.put(key, jsonObject.getString(key)); } // 请求,获取结果 actual = HttpRequestUtil.sendRequest(url, requestType, params); logger.info("k-v请求返回结果: " + actual); }
结果演示
测试数据
运行testng.xml结果
__EOF__
![微信:ren168632201](https://files-cdn.cnblogs.com/files/uncleyong/wx.bmp)
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!