如何使Http调用更加抽象?

时间:2018-01-09 22:55:59

标签: java rest rest-assured

目前这是我的代码,它具有相同的代码,只有POST和PUT是不同的:

private static Response putRequest(String endpoint, T request, int code, String uuid) {
    return Response(buildRequest().body(request).put(endpoint + "/{uuid}", uuid), code);
}

AND

private static Response postRequest(String endpoint, T request, int code, String uuid){
    return Response(buildRequest().body(request).post(endpoint + "/{uuid}",uuid), code);
}

如何使调用通用? Request参数是通用的,具有更大的灵活性。

2 个答案:

答案 0 :(得分:0)

要在静态方法中使用泛型类型,您需要在静态方法的签名中包含泛型声明。这是通过在返回类型之前插入<T>来完成的。

要制作所需的通用静态,您需要将其中一个方法更改为:

private static Response postRequest(String endpoint, T request, int code, String uuid) {
    return Response(buildRequest().body(request).post(endpoint + "/{uuid}",uuid), code);
}

private static <T> Response postRequest(String endpoint, T request, int code, String uuid){
    return Response(buildRequest().body(request).post(endpoint + "/{uuid}",uuid), code);
}

答案 1 :(得分:-1)

我假设你想在这里尽可能多地重用。如果是这种情况,您可以将postput操作包装到功能界面中。

public static interface RequestOperation{

    public Request operation(Request r, String s1, String s2);
}

public static <T> Response putRequest(String endpoint, T request, int code, String uuid) {
    return request ( (r, s1, s2) -> r.post(s1, s2), endpoint, request, code, uuid );
}

public static <T> Response postRequest(String endpoint, T request, int code, String uuid){
    return request ( (r, s1, s2) -> r.post(s1, s2), endpoint, request, code, uuid );
}

public static <T> Response request(RequestOperation requestOperation, String endpoint, 
T request, int code, String uuid){        
    return new Response( 
    requestOperation.operation( buildRequest().body(request), endpoint + "/{uuid}",uuid), 
    code );
}

public static class Response{

    public Response(Request r, int code){}
}

public static class Request{

    public <T> Request body(T request){
        return this;
    }

    public Request post(String s, String s1){
        return this;
    }

    public Request put(String s, String s1){
        return this;
    }
}

public static Request buildRequest(){
    return new Request();
}