Java自动化测试(HttpClient 13)

时间:2022-07-22
本文章向大家介绍Java自动化测试(HttpClient 13),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

修改Maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>auto_api</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <!-- 文件拷贝时的编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- 编译时的编码 -->
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <aspectj.version>1.9.2</aspectj.version>
    </properties>

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

httpclient

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

http://www.lemfix.com/topics/363

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

发起Get请求

  1. 创建请求对象
  2. 设置请求方法
  3. 设置接口url地址
  4. 设置请求头
  5. 设置请求体(接口参数)
  6. 点击发送
  7. 获取响应对象
  8. 格式化响应对象(响应状态码,响应头,响应体)

请求必须由客户端发起(浏览器,jmeter,httpcline),必须创建一个客户端 execute(HttpUriRequest):多态方法,接受HttpUriRequest所有子实现

package com.zhongxin.demo;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
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 java.io.IOException;
import java.util.Arrays;

public class GetDemo {
    public static void main(String[] args) throws IOException {
        // 1+2+3
        HttpGet get = new HttpGet("http://api.lemonban.com/futureloan/loans");
        // 4
        get.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
        // 6 请求必须由客户端发起(浏览器,jmeter,httpcline),必须创建一个客户端
        HttpClient client = HttpClients.createDefault();
        // execute(HttpUriRequest):多态方法,接受HttpUriRequest所有子实现
        // 7
        HttpResponse response = client.execute(get);
        // 8
        // 响应状态码
        System.out.println(response.getStatusLine().getStatusCode());
        // 响应头
        Header[] allHeaders = response.getAllHeaders();
        System.out.println(Arrays.toString(allHeaders));
        // 响应体
        HttpEntity entity = response.getEntity();
        System.out.println(EntityUtils.toString(entity));
    }
}

发起Post请求

  1. 创建请求对象
  2. 设置请求方法
  3. 设置接口url地址
  4. 设置请求头
  5. 设置请求体(接口参数)
  6. 点击发送
  7. 获取响应对象
  8. 格式化响应对象(响应状态码,响应头,响应体)

和get请求类似,不过需要增加请求体:

StringEntity body = new StringEntity("{'membet_id':2060127,'amount':1}", "utf-8");
post.setEntity(body);
package com.zhongxin.demo;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;

public class PostDemo {
    public static void main(String[] args) throws IOException {
        // 1+2+3
        HttpPost post = new HttpPost("http://api.lemonban.com/futureloan/member/recharge");
        // 4
        post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
        post.setHeader("Content-Type", "application/json");
        // 5
        StringEntity body = new StringEntity("{"member_id":2060127,"amount":1}", "utf-8");
        post.setEntity(body);
        // 6 请求必须由客户端发起(浏览器,jmeter,httpcline),必须创建一个客户端
        HttpClient client = HttpClients.createDefault();
        // execute(HttpUriRequest):多态方法,接受HttpUriRequest所有子实现
        // 7
        HttpResponse response = client.execute(post);
        // 8
        // 响应状态码
        System.out.println(response.getStatusLine().getStatusCode());
        // 响应头
        Header[] allHeaders = response.getAllHeaders();
        System.out.println(Arrays.toString(allHeaders));
        // 响应体
        HttpEntity entity = response.getEntity();
        System.out.println(EntityUtils.toString(entity));
    }
}

封装

package com.zhongxin.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;

public class HttpUtils {
    /*
     * 发送get请求
     * @param url       接口地址
     * @throws
     * */
    public static void get(String url) throws Exception {
        HttpGet get = new HttpGet(url);
        get.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(get);
        printResponse(response);
    }


    /*
     * 发送一个post请求
     * @param url        接口地址
     * @param params     接口参数
     * @throws
     * */
    public static void post(String url, String params) throws Exception {
        HttpPost post = new HttpPost(url);
        post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
        post.setHeader("Content-Type", "application/json");
        StringEntity body = new StringEntity(params, "utf-8");
        post.setEntity(body);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        printResponse(response);
    }

    /**
     * 打印响应
     * @param response      响应对象
     * @return
     * @throws IOException
     */
    private static String printResponse(HttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        Header[] allHeaders = response.getAllHeaders();
        System.out.println(Arrays.toString(allHeaders));
        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println(body);
        return body;
    }
}

测试

package com.zhongxin.utils;

public class Demo {
    public static void main(String[] args) throws Exception {
        HttpUtils.get("http://api.lemonban.com/futureloan/loans");
        HttpUtils.get("http://api.lemonban.com/futureloan/loans?pageIndex=1");
        HttpUtils.get("http://api.lemonban.com/futureloan/loans?pageIndex=1&pageSize=1");

        HttpUtils.post("http://api.lemonban.com/futureloan/member/recharge", "{"member_id":2060127,"amount":1}");
        HttpUtils.post("http://api.lemonban.com/futureloan/member/recharge", "{"member_id":2060127,"amount":2}");
        HttpUtils.post("http://api.lemonban.com/futureloan/member/recharge", "{"member_id":2060127,"amount":-1}");
        HttpUtils.post("http://api.lemonban.com/futureloan/member/recharge", "{"member_id":2060127,"amount":"aaa"}");
    }
}