java类com.mashape.unirest.http.HttpMethod的实例源码

RestHelper.java 文件源码 项目:drinkwater-java 阅读 19 收藏 0 点赞 0 评论 0
public static HttpMethod mapToUnirestHttpMethod(drinkwater.rest.HttpMethod methodAsAnnotation) {
    switch (methodAsAnnotation.value().toUpperCase()) {
        case "GET":
            return HttpMethod.GET;
        case "POST":
            return HttpMethod.POST;
        case "DELETE":
            return HttpMethod.DELETE;
        case "PUT":
            return HttpMethod.PUT;
        case "PATCH":
            return HttpMethod.PATCH;
        default:
            throw new RuntimeException(String.format("could not map correct http method : %s", methodAsAnnotation.value()));
    }
}
TestApiBuilder.java 文件源码 项目:javalin 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void routesWithoutPathArg_works() throws Exception {
    app.routes(() -> {
        path("api", () -> {
            get(OK_HANDLER);
            post(OK_HANDLER);
            put(OK_HANDLER);
            delete(OK_HANDLER);
            patch(OK_HANDLER);
            path("user", () -> {
                get(OK_HANDLER);
                post(OK_HANDLER);
                put(OK_HANDLER);
                delete(OK_HANDLER);
                patch(OK_HANDLER);
            });
        });
    });
    HttpMethod[] httpMethods = new HttpMethod[]{HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.PATCH};
    for (HttpMethod httpMethod : httpMethods) {
        assertThat(call(httpMethod, "/api").getStatus(), is(200));
        assertThat(call(httpMethod, "/api/user").getStatus(), is(200));
    }
}
SwaggerGeneratorInput.java 文件源码 项目:api2swagger 阅读 19 收藏 0 点赞 0 评论 0
private SwaggerGeneratorInput(String endpoint, HttpMethod method, Map<String, String> pathParams, Map<String, String> headers, Map<String, Object> parameters, String swaggerJSONFilePath, 
        boolean isAuthentication, String username, String password, String host, String basePath, String apiPath, String apiName, String apiSummary, String apiDescription, List<String> apiTags){
    this.endpoint = endpoint;
    this.pathParams = pathParams;
    this.headers = headers;
    this.parameters = parameters;
    this.swaggerJSONFile = swaggerJSONFilePath;
    this.method = method;
    this.authentication = isAuthentication;
    this.username = username;
    this.password = password;
    this.host = host;
    this.basePath = basePath;
    this.apiPath = apiPath;
    this.apiName = apiName;
    this.apiSummary = apiSummary;
    this.apiDescription = apiDescription;
    this.apiTags = apiTags;
}
RestHelper.java 文件源码 项目:drinkwater-java 阅读 43 收藏 0 点赞 0 评论 0
public static HttpMethod mapToUnirestHttpMethod(drinkwater.rest.HttpMethod methodAsAnnotation) {
    switch (methodAsAnnotation.value().toUpperCase()) {
        case "GET":
            return HttpMethod.GET;
        case "POST":
            return HttpMethod.POST;
        case "DELETE":
            return HttpMethod.DELETE;
        case "PUT":
            return HttpMethod.PUT;
        case "PATCH":
            return HttpMethod.PATCH;
        default:
            throw new RuntimeException(String.format("could not map correct http method : %s", methodAsAnnotation.value()));
    }
}
RestHelper.java 文件源码 项目:drinkwater-java 阅读 20 收藏 0 点赞 0 评论 0
private static RestDefinition toRestdefinition(RouteBuilder builder,
                                               Method method,
                                               HttpMethod httpMethod,
                                               String restPath) {
    RestDefinition answer = builder.rest();

    String fromPath = restPath;

    if (httpMethod == HttpMethod.GET) {
        answer = answer.get(fromPath);
    } else if (httpMethod == HttpMethod.POST) {
        answer = answer.post(fromPath);
    } else if (httpMethod == HttpMethod.PUT) {
        answer = answer.put(fromPath);
    } else if (httpMethod == HttpMethod.DELETE) {
        answer = answer.delete(fromPath);
    } else if (httpMethod == HttpMethod.PATCH) {
        answer = answer.patch(fromPath);
    } else {
        throw new RuntimeException("method currently not supported in Rest Paths : " + httpMethod);
    }

    answer = setBodyType(answer, method);

    return answer;
}
KintoClientTest.java 文件源码 项目:kinto-http-java 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void testRequestWithoutCustomHeaders() {
    // GIVEN a fake url
    String remote = "https://fake.kinto.url";
    // AND a kintoClient
    KintoClient kintoClient = new KintoClient(remote);
    // AND an ENDPOINTS
    ENDPOINTS endpoint = ENDPOINTS.GROUPS;
    // WHEN calling request
    GetRequest request = kintoClient.request(endpoint);
    // THEN the root part is initialized
    assertThat(request.getUrl(), is(remote + "/buckets/{bucket}/groups"));
    // AND the get http method is used
    assertThat(request.getHttpMethod(), is(HttpMethod.GET));
    // AND the default headers are set
    assertThat(request.getHeaders(), is(defaultHeaders));
}
KintoClientTest.java 文件源码 项目:kinto-http-java 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void testRequestWithCustomHeaders() {
    // GIVEN a fake url
    String remote = "https://fake.kinto.url";
    // AND custom headers
    Map<String, String> customHeaders = new HashMap<>();
    customHeaders.put("Authorization", "Basic supersecurestuff");
    customHeaders.put("Warning", "Be careful");
    customHeaders.put("Accept", "application/html");
    // AND expected headers
    Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders);
    customHeaders.forEach((k, v) -> expectedHeaders.merge(k, Arrays.asList(v), (a, b) -> a.addAll(b) ? a:a));
    // AND a kintoClient
    KintoClient kintoClient = new KintoClient(remote, customHeaders);
    // AND an ENDPOINTS
    ENDPOINTS endpoint = ENDPOINTS.GROUPS;
    // WHEN calling request
    GetRequest request = kintoClient.request(endpoint);
    // THEN the root part is initialized
    assertThat(request.getUrl(), is(remote + "/buckets/{bucket}/groups"));
    // AND the get http method is used
    assertThat(request.getHttpMethod(), is(HttpMethod.GET));
    // AND the default headers are set
    assertThat(request.getHeaders(), is(expectedHeaders));
}
HttpClient.java 文件源码 项目:raptor 阅读 292 收藏 0 点赞 0 评论 0
/**
 * Perform a request with body to the API
 *
 * @param httpMethod
 * @param url path of request
 * @param body content to be sent
 * @param opts
 * @return the request response
 */
public JsonNode request(HttpMethod httpMethod, String url, JsonNode body, RequestOptions opts) {

    if (opts == null) {
        opts = RequestOptions.defaults();
    }

    prepareRequest();
    HttpRequestWithBody req = createRequest(httpMethod, url, opts);

    if (body != null) {
        req.body(body);
    }

    return tryRequest(req, opts);
}
Client.java 文件源码 项目:gatekeeper 阅读 27 收藏 0 点赞 0 评论 0
public String get(String key) throws Exception {
    HttpRequest request = new HttpRequestWithBody(
        HttpMethod.GET,
        makeConsulUrl(key) + "?raw"
    ).getHttpRequest();

    authorizeHttpRequest(request);

    HttpResponse<String> response;

    try {
        response = HttpClientHelper.request(request, String.class);
    } catch (Exception exception) {
        throw new ConsulException("Consul request failed", exception);
    }

    if (response.getStatus() == 404) {
        return null;
    }

    String encrypted = response.getBody();

    return encryption.decrypt(encrypted);
}
RestAction.java 文件源码 项目:cognitivej 阅读 18 收藏 0 点赞 0 评论 0
private T doWork() {
    try {
        setupErrorHandlers();
        WorkingContext workingContext = workingContext();
        HttpRequest builtRequest = buildUnirest(workingContext)
                .queryString(workingContext.getQueryParams())
                .headers(workingContext.getHeaders()).header("Ocp-Apim-Subscription-Key", cognitiveContext.subscriptionKey);
        if (!workingContext.getHttpMethod().equals(HttpMethod.GET) && workingContext().getPayload().size() > 0) {
            buildBody((HttpRequestWithBody) builtRequest);
        }
        HttpResponse response;
        if (typedResponse() == InputStream.class)
            response = builtRequest.asBinary();
        else
            response = builtRequest.asString();

        checkForError(response);
        return postProcess(typeResponse(response.getBody()));
    } catch (UnirestException | IOException e) {
        throw new CognitiveException(e);
    }
}
RestHelper.java 文件源码 项目:drinkwater-java 阅读 21 收藏 0 点赞 0 评论 0
public static HttpMethod httpMethodFor(Method method) {

        HttpMethod defaultHttpMethod = HttpMethod.GET;

        drinkwater.rest.HttpMethod methodAsAnnotation = method.getDeclaredAnnotation(drinkwater.rest.HttpMethod.class);

        if (methodAsAnnotation != null) {
            return mapToUnirestHttpMethod(methodAsAnnotation);
        }

        return List.ofAll(prefixesMap.entrySet())
                .filter(prefix -> startsWithOneOf(method.getName(), prefix.getValue()))
                .map(entryset -> entryset.getKey())
                .getOrElse(defaultHttpMethod);
    }
RestHelper.java 文件源码 项目:drinkwater-java 阅读 21 收藏 0 点赞 0 评论 0
private static String restPath(Method method, HttpMethod httpMethod) {
    if (httpMethod == HttpMethod.OPTIONS) {
        return "";
    }
    String fromPath = getPathFromAnnotation(method);

    if (fromPath == null || fromPath.isEmpty()) {
        fromPath = List.of(prefixesMap.get(httpMethod))
                .filter(prefix -> method.getName().toLowerCase().startsWith(prefix))
                .map(prefix -> method.getName().replace(prefix, "").toLowerCase())
                .getOrElse("");

        //if still empty
        if (fromPath.isEmpty()) {
            fromPath = method.getName();
        }
    }

    if (httpMethod == HttpMethod.GET) {
        if (fromPath == null || fromPath.isEmpty()) {
            fromPath = javaslang.collection.List.of(method.getParameters())
                    .map(p -> "{" + p.getName() + "}").getOrElse("");
        }
    }

    return fromPath;
}
RestHelper.java 文件源码 项目:drinkwater-java 阅读 19 收藏 0 点赞 0 评论 0
private static RestDefinition toRestdefinition(RouteBuilder builder,
                                               Method method,
                                               HttpMethod httpMethod,
                                               String restPath) {
    RestDefinition answer = builder.rest();

    String fromPath = restPath;

    if (httpMethod == HttpMethod.GET) {
        answer = answer.get(fromPath);
    } else if (httpMethod == HttpMethod.POST) {
        answer = answer.post(fromPath);
    } else if (httpMethod == HttpMethod.PUT) {
        answer = answer.put(fromPath);
    } else if (httpMethod == HttpMethod.DELETE) {
        answer = answer.delete(fromPath);
    } else if (httpMethod == HttpMethod.PATCH) {
        answer = answer.patch(fromPath);
    } else {
        throw new RuntimeException("method currently not supported in Rest Paths : " + httpMethod);
    }

    answer = setBodyType(answer, method);

    return answer;
}
MethodToRestParameters.java 文件源码 项目:drinkwater-java 阅读 29 收藏 0 点赞 0 评论 0
private void init() {
    HttpMethod httpMethod = httpMethodFor(method);
    List<Parameter> parameterInfos = javaslang.collection.List.of(method.getParameters());
    NoBody noBodyAnnotation = method.getAnnotation(NoBody.class);

    hasReturn = returnsVoid(method);

    if (parameterInfos.size() == 0) {
        return;
    }

    if (httpMethod == HttpMethod.GET) {
        hasBody = false;
    } else if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.DELETE || httpMethod == HttpMethod.PUT) {
        if (parameterInfos.size() > 0) {
            hasBody = true;
        }
        if (noBodyAnnotation != null) {
            hasBody = false;
        }
    } else {
        throw new RuntimeException("come back here : MethodToRestParameters.init()");
    }

    if (hasBody) { // first parameter of the method will be assigned with the body content
        headerNames = parameterInfos.tail().map(p -> mapName(p)).toList();
    } else {

        headerNames = parameterInfos.map(p -> mapName(p)).toList();
    }

}
TestTranslators.java 文件源码 项目:javalin 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void test_json_jackson_throwsForBadObject() throws Exception {
    app.get("/hello", ctx -> ctx.status(200).json(new TestObject_NonSerializable()));
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(500));
    assertThat(response.getBody(), is("Internal server error"));
}
TestTranslators.java 文件源码 项目:javalin 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void test_json_jacksonMapsJsonToObject_throwsForBadObject() throws Exception {
    app.get("/hello", ctx -> ctx.json(ctx.bodyAsClass(TestObject_NonSerializable.class).getClass().getSimpleName()));
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(500));
    assertThat(response.getBody(), is("Internal server error"));
}
TestFilters.java 文件源码 项目:javalin 阅读 28 收藏 0 点赞 0 评论 0
@Test
public void test_justFilters_is404() throws Exception {
    Handler emptyHandler = ctx -> {
    };
    app.before(emptyHandler);
    app.after(emptyHandler);
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(404));
    assertThat(response.getBody(), is("Not found"));
}
TestHaltException.java 文件源码 项目:javalin 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void test_haltBeforeWildcard_works() throws Exception {
    app.before("/admin/*", ctx -> {
        throw new HaltException(401);
    });
    app.get("/admin/protected", ctx -> ctx.result("Protected resource"));
    HttpResponse<String> response = call(HttpMethod.GET, "/admin/protected");
    assertThat(response.getStatus(), is(401));
    assertThat(response.getBody(), not("Protected resource"));
}
TestHaltException.java 文件源码 项目:javalin 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void test_haltInRoute_works() throws Exception {
    app.get("/some-route", ctx -> {
        throw new HaltException(401, "Stop!");
    });
    HttpResponse<String> response = call(HttpMethod.GET, "/some-route");
    assertThat(response.getBody(), is("Stop!"));
    assertThat(response.getStatus(), is(401));
}
TestHaltException.java 文件源码 项目:javalin 阅读 26 收藏 0 点赞 0 评论 0
@Test
public void test_afterRuns_afterHalt() throws Exception {
    app.get("/some-route", ctx -> {
        throw new HaltException(401, "Stop!");
    }).after(ctx -> {
        ctx.status(418);
    });
    HttpResponse<String> response = call(HttpMethod.GET, "/some-route");
    assertThat(response.getBody(), is("Stop!"));
    assertThat(response.getStatus(), is(418));
}
TestHttpVerbs.java 文件源码 项目:javalin 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void test_all_mapped_verbs_ok() throws Exception {
    app.get("/mapped", OK_HANDLER);
    app.post("/mapped", OK_HANDLER);
    app.put("/mapped", OK_HANDLER);
    app.delete("/mapped", OK_HANDLER);
    app.patch("/mapped", OK_HANDLER);
    app.head("/mapped", OK_HANDLER);
    app.options("/mapped", OK_HANDLER);
    for (HttpMethod httpMethod : HttpMethod.values()) {
        assertThat(call(httpMethod, "/mapped").getStatus(), is(200));
    }
}
TestResponse.java 文件源码 项目:javalin 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void test_resultString() throws Exception {
    app.get("/hello", ctx ->
        ctx.status(418)
            .result(MY_BODY)
            .header("X-HEADER-1", "my-header-1")
            .header("X-HEADER-2", "my-header-2"));
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(418));
    assertThat(response.getBody(), is(MY_BODY));
    assertThat(response.getHeaders().getFirst("X-HEADER-1"), is("my-header-1"));
    assertThat(response.getHeaders().getFirst("X-HEADER-2"), is("my-header-2"));
}
TestResponse.java 文件源码 项目:javalin 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void test_resultStream() throws Exception {
    byte[] buf = new byte[65537]; // big and not on a page boundary
    new Random().nextBytes(buf);
    app.get("/stream", ctx -> ctx.result(new ByteArrayInputStream(buf)));
    HttpResponse<String> response = call(HttpMethod.GET, "/stream");

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    assertThat(IOUtils.copy(response.getRawBody(), bout), is(buf.length));
    assertThat(buf, equalTo(bout.toByteArray()));
}
TestResponse.java 文件源码 项目:javalin 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void test_redirectWithStatus() throws Exception {
    app.get("/hello", ctx -> ctx.redirect("/hello-2", 302));
    app.get("/hello-2", ctx -> ctx.result("Redirected"));
    Unirest.setHttpClient(noRedirectClient); // disable redirects
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(302));
    Unirest.setHttpClient(defaultHttpClient); // re-enable redirects
    response = call(HttpMethod.GET, "/hello");
    assertThat(response.getBody(), is("Redirected"));
}
TestResponse.java 文件源码 项目:javalin 阅读 101 收藏 0 点赞 0 评论 0
@Test
public void test_createCookie() throws Exception {
    app.post("/create-cookies", ctx -> ctx.cookie("name1", "value1").cookie("name2", "value2"));
    HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies");
    List<String> cookies = response.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem("name1=value1"));
    assertThat(cookies, hasItem("name2=value2"));
}
TestResponse.java 文件源码 项目:javalin 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void test_deleteCookie() throws Exception {
    app.post("/create-cookie", ctx -> ctx.cookie("name1", "value1"));
    app.post("/delete-cookie", ctx -> ctx.removeCookie("name1"));
    HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies");
    List<String> cookies = response.getHeaders().get("Set-Cookie");
    assertThat(cookies, is(nullValue()));
}
TestResponse.java 文件源码 项目:javalin 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void test_cookieBuilder() throws Exception {
    app.post("/create-cookie", ctx -> {
        ctx.cookie(CookieBuilder.cookieBuilder("Test", "Tast"));
    });
    HttpResponse<String> response = call(HttpMethod.POST, "/create-cookie");
    List<String> cookies = response.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem("Test=Tast"));
}
RestHelper.java 文件源码 项目:drinkwater-java 阅读 22 收藏 0 点赞 0 评论 0
public static HttpMethod httpMethodFor(Method method) {

        HttpMethod defaultHttpMethod = HttpMethod.GET;

        drinkwater.rest.HttpMethod methodAsAnnotation = method.getDeclaredAnnotation(drinkwater.rest.HttpMethod.class);

        if (methodAsAnnotation != null) {
            return mapToUnirestHttpMethod(methodAsAnnotation);
        }

        return List.ofAll(prefixesMap.entrySet())
                .filter(prefix -> startsWithOneOf(method.getName(), prefix.getValue()))
                .map(entryset -> entryset.getKey())
                .getOrElse(defaultHttpMethod);
    }
RestHelper.java 文件源码 项目:drinkwater-java 阅读 22 收藏 0 点赞 0 评论 0
private static String restPath(Method method, HttpMethod httpMethod) {
    if (httpMethod == HttpMethod.OPTIONS) {
        return "";
    }
    String fromPath = getPathFromAnnotation(method);

    if (fromPath == null || fromPath.isEmpty()) {
        fromPath = List.of(prefixesMap.get(httpMethod))
                .filter(prefix -> method.getName().toLowerCase().startsWith(prefix))
                .map(prefix -> method.getName().replace(prefix, "").toLowerCase())
                .getOrElse("");

        //if still empty
        if (fromPath.isEmpty()) {
            fromPath = method.getName();
        }
    }

    if (httpMethod == HttpMethod.GET) {
        if (fromPath == null || fromPath.isEmpty()) {
            fromPath = javaslang.collection.List.of(method.getParameters())
                    .map(p -> "{" + p.getName() + "}").getOrElse("");
        }
    }

    return fromPath;
}
MethodToRestParameters.java 文件源码 项目:drinkwater-java 阅读 32 收藏 0 点赞 0 评论 0
private void init() {
    HttpMethod httpMethod = httpMethodFor(method);
    List<Parameter> parameterInfos = javaslang.collection.List.of(method.getParameters());
    NoBody noBodyAnnotation = method.getAnnotation(NoBody.class);

    hasReturn = returnsVoid(method);

    if (parameterInfos.size() == 0) {
        return;
    }

    if (httpMethod == HttpMethod.GET) {
        hasBody = false;
    } else if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.DELETE || httpMethod == HttpMethod.PUT) {
        if (parameterInfos.size() > 0) {
            hasBody = true;
        }
        if (noBodyAnnotation != null) {
            hasBody = false;
        }
    } else {
        throw new RuntimeException("come back here : MethodToRestParameters.init()");
    }

    if (hasBody) { // first parameter of the method will be assigned with the body content
        headerNames = parameterInfos.tail().map(p -> mapName(p)).toList();
    } else {

        headerNames = parameterInfos.map(p -> mapName(p)).toList();
    }

}


问题


面经


文章

微信
公众号

扫码关注公众号