首页 > 解决方案 > Java HTTP library to request an OpenAPI token and issue Authorized requests

问题描述


I need to perform a set of HTTP Operations which include a POST with Form Parameters and a GET using HTTP Headers to set the Authorization Header:

public void testResourceIsSecured() {
    String authResponse = ClientBuilder.newClient()
            .target("http://localhost:8080/auth/realms/thorntail-cmd-client/protocol/openid-connect/token")
            .request()
            .post(Entity.form(new Form()
                    .param("grant_type", "password")
                    .param("client_id", "thorntail-cmd-client-example")
                    .param("username", "user1")
                    .param("password", "password1")
            ), String.class);
    String accessToken = getAccessTokenFromResponse(authResponse);

    String serviceResponse = ClientBuilder.newClient()
            .target("http://localhost:8080/mpjwt/secured")
            .request()
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken)
            .get(String.class);
    Assert.assertEquals("Hi user1, this resource is secured", serviceResponse);
}

private String getAccessTokenFromResponse(String response) {
    String tokenStart = response.substring("{\"access_token\":\"".length());
    return tokenStart.substring(0, tokenStart.indexOf("\""));
}

The above code works with Resteasy client API, though I'm not allowed to use this library because of the dependencies it brings in. Which Java HTTP library would you advice to use as replacement, which brings the least amount of dependencies in? Thanks

标签: java

解决方案


You could try RestAssured. Not sure if it's dependencies fit better to your needs. It can be used to test API's and therefore it can be used as well as a simple REST client.


推荐阅读