基于restassured封装http工具类

<?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>con.aa</groupId>
    <artifactId>ss-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>


        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.11.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.13</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.30</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.24</version>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-path</artifactId>
            <version>4.3.0</version>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.3.0</version>
        </dependency>


        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>4.3.0</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.0.7</version>
        </dependency>

        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.25</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.8.0</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.7.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.26</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.13.2</version>
        </dependency>


   




     

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.15</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <suiteXmlFiles>
                        <suiteXmlFile>testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <properties>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>true</value>
                        </property>
                    </properties>
                    <workingDirectory>target/</workingDirectory>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>


@Slf4j
public class RestClient {
    private static final Base64.Encoder base64Encoder = Base64.getEncoder();

    public static String request(String url, Map<String, Object> params, Object object) {
        Map<String, Object> httpMap = getHttp();
        HttpMethodEnum method = (HttpMethodEnum) httpMap.get("httpMethod");
        Zen zen = zen((ZenEnum) httpMap.get("zen"));

        url = zen.getUri() + url;
        Map<String, String> headers = getHeaders(zen, method, url);
        headers = consoleHeaders((ZenEnum) httpMap.get("zen"), headers);
        url = url(zen, url, params, httpMap);

        RequestSpecification requestSpecification = given();

        requestSpecification = body(object, requestSpecification);

        requestSpecification = uploadFile(url, requestSpecification, headers);

        requestSpecification = requestSpecification.headers(headers);


        Response response = requestSpecification.request(method.toString(), url);
        log.info("httpCode===>{},resp====>{}", response.statusCode(), response.asString());

        log.info("headers===>{}", headers.toString());
        return response.asString();
    }


    public static String getAuthorization(Zen zen, String url, HttpMethodEnum method, String timeStamp) {
        String accessInfo = method + "\n" + timeStamp + "\n" + url;
        String signature = base64Encoder.encodeToString(HmacUtils.hmacSha1(zen.getAccount().getAccessKey(), accessInfo));
        String authorization = zen.getAccount().getAccessId() + ":" + signature;
        return authorization;
    }


    private static Map<String, String> getHeaders(Zen zen, HttpMethodEnum method, String url) {
        String xRequestId = "xRequestId-AutoTestCase-" + System.currentTimeMillis();
        log.info("xRequestId=>{}", xRequestId);
        String timeStamp = ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT);
        String authorization = getAuthorization(zen, url, method, timeStamp);

        Map<String, String> headers = new HashMap<>();
        headers.put("xRequestId", xRequestId);

        String ContentType = "application/json";
        if (url.contains("orchestration")) {
            ContentType = "text/plain;charset=utf-8";

            headers.put("X-Zenlayer-User-Id", "1");
        }
        headers.put("Content-type", ContentType);

        headers.put("Accept", "application/json");
 
        headers.put("Date", timeStamp);


        return headers;
    }


    private static Map<String, Object> getHttp() {
        Map<String, Object> map = new HashMap<>();

        StackTraceElement stack[] = (new Throwable()).getStackTrace();
        StackTraceElement ste = stack[2];

        Class<?> clazz = null;
        Method[] methods = null;
        try {
            clazz = Class.forName(ste.getClassName());
            methods = clazz.getMethods();
        } catch (Exception e) {
        }
        ZenEnum zen = clazz.getAnnotation(HttpBase.class).zen();

        HttpMethodEnum httpMethod = null;
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(ste.getMethodName())) {
                httpMethod = method.getAnnotation(HttpBase.class).method();
                description = method.getAnnotation(HttpBase.class).description();
            }
        }
        map.put("zen", zen);
        map.put("httpMethod", httpMethod);
        map.put("description", description);
        return map;
    }


    private static String paramsTransUrl(Map<String, Object> paraMap) {
        List<String> keys = new ArrayList<>(paraMap.keySet());
        Collections.sort(keys);
        String prestr = "?";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            Object value = paraMap.get(key);
            if (i == keys.size() - 1) {   //拼接时,不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    public static RequestSpecification uploadFile(String url, RequestSpecification requestSpecification, Map<String, String> headers) {
        if (url.contains("/loa/upload/")) {
            headers.remove("Content-type");
            headers.remove("Accept");
            File file = new File(System.currentTimeMillis() + "");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            requestSpecification = requestSpecification.multiPart("file", file);
        }
        return requestSpecification;
    }

    public static RequestSpecification body(Object object, RequestSpecification requestSpecification) {
        if (object != null) {
            String body = "";
            if (object.getClass().equals(ArrayList.class)) {
                body = JSONUtil.parseArray(object).toString();
            } else if (object.getClass().equals(String.class)) {
                body = object.toString();
            } else {
                body = JSONUtil.parseObj(object).toString();
            }
            requestSpecification = requestSpecification.body(body);
            log.info("body====>{}", body);
        }
        return requestSpecification;
    }

    public static String url(Zen zen, String url, Map<String, Object> params, Map<String, Object> httpMap) {
        HttpMethodEnum method = (HttpMethodEnum) httpMap.get("httpMethod");
        String description = (String) httpMap.get("description");

        String host = zen.getHost();

        if (params == null) {
            params = new HashMap<>();
        }
        params.put("userId", zen.getAccount().getUser());
        url = host + url + paramsTransUrl(params);
        log.info("url====>{}  method====>{} description=====>{}", url, method.toString(), description);

        return url;
    }

    public static Zen zen(ZenEnum zenEnum) {
        Zen zen = null;
        switch (zenEnum) {
            case dsdd:
                zen = ConfigUtil.getInstance().geConfigYaml().sss();
                break;
    
        }

        return zen;
    }

    public static Map<String, String> consoleHeaders(ZenEnum zenEnum, Map<String, String> headers) {
        if (zenEnum == ZenEnum.sss) {
   
        }
        return headers;
    }
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface HttpBase {
    ZenEnum zen() default zenconsol;

    HttpMethodEnum method() default GET;

    String description() default "";
}

public enum HttpMethodEnum {

    GET,
    PUT,
    POST,
    DELETE
}

    @HttpBase(method = GET, description = "")
    public static String getId(String vpnId) {

        return RestClient.request(url, null, null);
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值