自动化 手把手教你用 java 写 Postman

    技术2022-07-10  108

    自动化 手把手教你用 java 写 Postman

    Postman相信大家都听过或者用过,是一款能够模拟http请求的工具,它是由google开发的一款测试插件,最开始是chrome的一款插件,现在独立成一个应用了。有着许多优点,如免费开源,界面友好,操作简单。 说到底Postman是一款软件工具,那么只要是软件都是用代码写出来的。咱们今天就使用java中的httpclient工具包来模拟写一个Postman。

    1、首先我们创建一个maven项目,导入httpClient 坐标。

    <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> </dependencies>

    2、所有的代码都是由思路转化,所以我们先把思路整理下。

    1、打开postman 2、创建request连接 3、填写url和请求方式 4、如果有参数添加参数 5、点击发送按钮,发送请求 6、获取响应报文 7、格式化响应报文 8、在控制台输出报文

    3、首先我们先实现GET请求

    //1、打开postman //这一步相当于运行main方法。 //2、创建request连接 3、填写url和请求方式 HttpGet get = new HttpGet("https://www.baidu.com"); //4、如果有参数添加参数 get请求不需要参数,省略 CloseableHttpClient client = HttpClients.createDefault(); //5、点击发送按钮,发送请求 6、获取响应报文 CloseableHttpResponse response = client.execute(get); //7、格式化响应报文 HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); //8、在控制台输出报文 System.out.println(result);

    4、控制台结果结果 5、接下来再实现POST请求,实现思路和GET是一样的只是替换一些代码

    //1、打开postman //这一步相当于运行main方法。 //2、创建request连接 3、填写url和请求方式 HttpPost httpPost = new HttpPost("http://test.lemonban.com/ningmengban/mvc/user/login.json"); //2.1 额外设置Content-Type请求头 httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); //4、如果有参数添加参数 CloseableHttpClient client = HttpClients.createDefault(); httpPost.setEntity(new StringEntity("username=13212312312&password=4297f44b13955235245b2497399d7a93","UTF-8")); //5、点击发送按钮,发送请求 6、获取响应报文 CloseableHttpResponse response = client.execute(httpPost); //7、格式化响应报文 HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); //8、在控制台输出报文 System.out.println(result);

    6、控制台结果结果 7、如果我们想对一个接口进行重复测试,难道代码需要重写编写吗?不用,进一步封装优化即可。

    public static void main(String[] args) throws Exception{ String 请求地址 = "http://test.lemonban.com/ningmengban/mvc/user/login.json"; String 请求参数1 = "username=13212312312&password=4297f44b13955235245b2497399d7a93"; String 请求参数2 = "username=13212312312&password=33333"; String 请求参数3 = "password=123456"; String 请求参数4 = "username=13212312312"; 发起post请求(请求地址,请求参数1); 发起post请求(请求地址,请求参数2); 发起post请求(请求地址,请求参数3); 发起post请求(请求地址,请求参数4); } private static void 发起post请求(String url,String params) throws IOException, ClientProtocolException { //1、打开postman --->编程语言写得 //2、创建request连接 3、填写url和请求方式 HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); //4、如果有参数添加参数 CloseableHttpClient client = HttpClients.createDefault(); httpPost.setEntity(new StringEntity(params,"UTF-8")); //5、点击发送按钮,发送请求 6、获取响应报文 CloseableHttpResponse response = client.execute(httpPost); //7、格式化响应报文 HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); System.out.println(result); }
    Processed: 0.013, SQL: 9