HttpRequest的使用之Python VS Java

Posted pealy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpRequest的使用之Python VS Java相关的知识,希望对你有一定的参考价值。

主要想对最近分别用Python和Java去实现HttpRequest做个记录总结:

Python:common类里面定义好了get,post

import requests


# 定义一个common的类,它的父类是object
class Common(object):
  # common的构造函数
  def __init__(self):
    # 被测系统的根路由
    self.url_root = \'http://localhost:3000\'
  # 封装你自己的get请求,uri是访问路由,params是get请求的参数,如果没有默认为空
  def get(self, uri, params=\'\'):
    # 拼凑访问地址
    url = self.url_root + uri + params
    # 通过get请求访问对应地址
    res = requests.get(url)
    # 返回request的Response结果,类型为requests的Response类型
    return res
  # 封装你自己的post方法,uri是访问路由,params是post请求需要传递的参数,如果没有参数这里为空
  def post(self, uri, params=\'\'):
    # 拼凑访问地址
    url = self.url_root + uri
    if len(params) > 0:
      # 如果有参数,那么通过post方式访问对应的url,并将参数赋值给requests.post默认参数data
      # 返回request的Response结果,类型为requests的Response类型
      res = requests.post(url, data=params)
    else:
      # 如果无参数,访问方式如下
      # 返回request的Response结果,类型为requests的Response类型
      res = requests.post(url)
    return res
View Code

其中调用get:

运行效果如下:

 

 调用post,运行效果如下:

 

 Part2: java 对httpRequest封装 实现

package common;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

import java.util.Map;

import static io.restassured.RestAssured.given;

public class APIRunner {

    private  static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(APIRunner.class);
    private String baseURI="";

    public  static Response httpGet(String basePath, Map header)
    {
        log.info("base site is:"+ RestAssured.baseURI);
        log.info("api path is:"+basePath+"and method is get");

        RestAssured.baseURI="";
        header.forEach((k,v)->log.info("header key="+k+"value="+v));
        Response response=null;
        RequestSpecification state=given().contentType("application/json;charset=UTF-8");
        if(header.size()>0){
            state=state.headers(header);
        }
        response=baseRun("get",basePath,"",state);
        return response;

    }

    public static Response httpGet(String basePath, Map header,Map parmas){
        log.info("base site is:"+ RestAssured.baseURI);
        log.info("api path is:"+basePath+"and method is get");

        RestAssured.baseURI="";
        header.forEach((k,v)->log.info("header key="+k+"value="+v));
        parmas.forEach((k,v)->log.info("parmas key="+k+"value="+v));

        Response response=null;
        RequestSpecification state=given().contentType("application/json;charset=UTF-8");
        if(header.size()>0){
            state=state.headers(header);
        }
        if(parmas.size()>0)
        {
            state=state.params(parmas);
        }
        response=baseRun("get",basePath,"",state);
        return response;

    }

    public static Response httpGet(String basePath, Map pathParams,Map header,Map parmas){
        log.info("base site is:"+ RestAssured.baseURI);
        log.info("api path is:"+basePath+"and method is get");

        RestAssured.baseURI="";
        header.forEach((k,v)->log.info("header key="+k+"value="+v));
        pathParams.forEach((k,v)->log.info("path parameters key="+k+"value="+v));
        parmas.forEach((k,v)->log.info("parmas key="+k+"value="+v));

        Response response=null;
        RequestSpecification state=given().contentType("application/json;charset=UTF-8");
        if(header.size()>0){
            state=state.headers(header);
        }
        if(parmas.size()>0)
        {
            state=state.params(parmas);
        }
        if(pathParams.size()>0)
        {
            state=state.pathParams(pathParams);
        }
        response=baseRun("get",basePath,"",state);
        return response;

    }

    public static Response httpPostFromData(String basePath,Map forms)
    {
        log.info("base site is:"+RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        RestAssured.baseURI="";
        forms.forEach((k,v)->log.info("from data key="+k+"value="+v));
        Response response=null;

        RequestSpecification state=given();
        response=state
                .request()
                .formParams(forms)
                .post(basePath);
        return response;
    }

    public static Response httpPost(String basePath,String body)
    {
        log.info("base site is:"+RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        RestAssured.baseURI="";

        Response response=null;

        RequestSpecification state=given().contentType("application/json;charset=UTF-8");
        response=baseRun("post",basePath,body,state);
        return response;
    }

    public static Response httpPostFormData(String basePath, Map header, Map forms){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        forms.forEach((k, v) -> log.info("form data key = " + k + " value = " + v));
        Response response = null;
        RequestSpecification state = given().contentType("application/x-www-form-urlencoded; charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        response = state
                .formParams(forms)
                .request()
                .post(basePath);
        return response;
    }

    public Response httpPostFormData(String basePath, Map header, Map params, Map forms){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        params.forEach((k, v) -> log.info("query parameters data key = " + k + " value = " + v));
        forms.forEach((k, v) -> log.info("form data key = " + k + " value = " + v));
        Response response = null;
        RequestSpecification state = given().contentType("application/x-www-form-urlencoded; charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        response = state
                .params(params)
                .formParams(forms)
                .request()
                .post(basePath);
        return response;
    }

    public Response httpPost(String basePath, Map header, String body){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        RestAssured.baseURI = "";
        if(body.length() > 0){
            log.info("request body is: " + body);
        }
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        response = baseRun("post", basePath, body, state);
        return response;
    }

    public Response httpPost(String basePath, Map header, Map pathParams, String body){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: post");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        pathParams.forEach((k, v) -> log.info("path parameters key = "+ k + " value = " + v));
        if(body.length() > 0){
            log.info("request body is: " + body);
        }
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        if(pathParams.size() > 0){
            state = state.pathParams(pathParams);
        }
        response = baseRun("post", basePath, body, state);
        return response;
    }

    public Response httpPut(String basePath, String body){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: put");
        RestAssured.baseURI = "";
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        response = baseRun("put", basePath, body, state);
        return response;
    }

    public static Response httpPut(String basePath, Map header, String body){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: put");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        response = baseRun("put", basePath, body, state);
        return response;
    }

    public Response httpPut(String basePath, Map header, Map pathParams, String body){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: put");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        pathParams.forEach((k, v) -> log.info("path parameters key = "+ k + " value = " + v));
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        if(pathParams.size() > 0){
            state = state.pathParams(pathParams);
        }
        response = baseRun("put", basePath, body, state);
        return response;
    }

    public Response httpDelete(String basePath, Map header){
        log.info("base site is: " + RestAssured.baseURI);
        log.info("api path is: "+ basePath + " and method is: delete");
        RestAssured.baseURI = "";
        header.forEach((k, v) -> log.info("header key = " + k + " value = " + v));
        Response response = null;
        RequestSpecification state = given().contentType("application/json;charset=UTF-8");
        if(header.size() > 0){
            state = state.headers(header);
        }
        response = baseRun("delete", basePath, "", state);
        return response;
    }

    private static Response baseRun(String requestMethod,String basePath,String bodyString,RequestSpecification state)
    {
        Response response;
        if(requestMethod.toLowerCase().equals("get")){
            response =state
                    .request()
                    .get(basePath);
        }else if(requestMethod.toLowerCase().equals("put")){
            response=state
                    .request()
                    .body(bodyString)
                    .put(basePath);
        }else if(requestMethod.toLowerCase().equals("delete")){
            response=state
                    .request()
                    .delete(basePath);
        }else if(requestMethod.toLowerCase().equals("post")){
            response=state
                    .request()
                    .body(bodyString)
                    .post(basePath);
        }else if(requestMethod.toLowerCase().equals("patch")){
            response=state
                    .request()
                    .body(bodyString)
                    .patch(basePath);
        }else {
            response = null;
        }
        return response;
    }
}
View Code

测试类实现:Get Post Put

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.APIRunner;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class APIRunnerTest {
    Map<String,String> header=new HashMap<>();

    @Test(description = "Test the search interface for douban", priority = 0)
    public  void Get_PostMan_By_Key() throws IOException {
        Map<String,String> params=new HashMap<>();
        params.put("test","123");

        Response res= APIRunner.httpGet("https://postman-echo.com/get",header,params);
        Assert.assertTrue(res.statusCode()==200);

        JSONObject jobject= JSON.parseObject(res.asString());
        JSONObject jobjectRes=(JSONObject)jobject.get("args");
        Assert.assertEquals(jobjectRes.toJSONString(),JSONObject.toJSONString(params));
    }

    @Test(description = "Test the search interface for douban", priority = 0)
    public  void Post_PostMan_By_Key() throws IOException {
        Map<String,String> params=new HashMap<>();
        params.put("test","abc");
        params.put("autotest","def");

        Response res= APIRunner.httpPostFormData("https://postman-echo.com/post",header,params);
        Assert.assertTrue(res.statusCode()==200);

        JSONObject jobject= JSON.parseObject(res.asString());
        JSONObject jobjectRes=(JSONObject)jobject.get("form");
        Assert.assertEquals(jobjectRes.toJSONString(),JSONObject.toJSONString(params));
    }

    @Test(description = "Test the search interface for douban", priority = 0)
    public  void Put_PostMan_By_Key() throws IOException {
        String params="Etiam mi lacus, cursus vitae felis et, blandit pellentesque neque. Vestibulum eget nisi a tortor commodo dignissim.";

        Response res= APIRunner.httpPut("https://postman-echo.com/put",header,params);
        Assert.assertTrue(res.statusCode()==200);

        JSONObject jobject= JSON.parseObject(res.asString());
        String jobjectRes=jobject.get("data").toString();
        Assert.assertEquals(jobjectRes,params);
    }
}
View Code

 

以上是关于HttpRequest的使用之Python VS Java的主要内容,如果未能解决你的问题,请参考以下文章

Python学习108天(Django之视觉函数)

为啥 autofac 在 HttpRequest 结束之前处理一个对象?

Swoole v4.6 版本新特性之 HttpRequest 增强

Django之views视图函数

python tornado获得多个异步httprequest的响应

Django之视图函数总结