How to retrieve an entity through REST for Dummies

hi out there, I am absolute beginner when it comes to REST. Following the documentation I tried to load an entity with the following code:

    String url = "http://localhost:8080/rest/entities/bookstore_EHC_Q_KFZA/" + getEditedEntity().getId() ;
    try {
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String body = response.getBody();
        MediaType contentType = response.getHeaders().getContentType();
        HttpStatus statusCode = response.getStatusCode();
        System.out.println("Erfolgreicher REST-Aufruf");
        System.out.println("MediaType:" + contentType.toString());
        System.out.println("HttpStatus:" + statusCode.toString());
        System.out.println("Body:" + body.toString());
        // Process the response...
    } catch (RestClientException e) {
        // Handle the exception...
        System.out.println(e.getMessage());
        System.out.println(e.getStackTrace());
    }

I receive an error code 401 stating: “{“error”:“unauthorized”,“error_description”:“Full authentication is required to access this resource”}”.

I understood, that I have to POST an authorization request prior to this GET request. Do you have a code sample to do this? The curl-sample in the documentation does not work for me.

Thx for any assistance

Michael

Hi Michael,

You need to authenticate first and then use the obtained token in API requests.

This is how you can authenticate using Java code:

public void test() {
    authenticate("client", "secret", "admin", "admin");
}

private String authenticate(String client, String secret, String username, String password) {
    HttpClient httpClient = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:8080/oauth/token"))
            .header("Authorization", getBasicAuthHeader(client, secret))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .POST(HttpRequest.BodyPublishers.ofString(getAuthRequestBody(username, password)))
            .build();
    try {
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == HttpStatus.OK.value()) {
            String responseText = response.body();
            System.out.println("Response: " + responseText);
            // Using Jackson to convert JSON responce to a map:
            Map<String, Object> map = new ObjectMapper().readValue(responseText, Map.class);
            String accessToken = (String) map.get("access_token");
            System.out.println("Access token: " + accessToken);
            return accessToken;
        } else {
            System.out.println("Error: " + response.statusCode());
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

private String getBasicAuthHeader(String client, String secret) {
    String str = client + ":" + secret;
    return "Basic " + Base64.getEncoder().encodeToString(str.getBytes());
}

private String getAuthRequestBody(String username, String password) {
    return "grant_type=password&username=" + username + "&password=" + password;
}

1 Like

Thank you Konstantin, that worked!

Now I can move on further.

best regards,

Michael