Java REST client - rewrite curl code into Java code

2.7k Views Asked by At

I am writing a simple REST client in Java that sends requests to a server and retrieve some data. The server uses a token for authorization which has to be included in header (according to documentation).

The problem is I am not sure how to rewrite it correctly correctly. I have a curl command that works well:

curl --include --header "authorization:a7b857f6.....rest of my token" --header "Content-Type: application/json" https://serverUrl/v1/search?q=someQuery

This request returns the correct answer (some results for a given query in this case).

I tried to rewrite this in Java but I am getting "404 - resource not found although" the query is the same.

public void getResultsByQuery() {
        Client client = ClientBuilder.newClient();
        Response response = client
                .target("https://serverUrl")
                .path("/v1/search?q=someQuery")
                .request("application/json")
                .header("Content-Type", "application/json")
                .header("authorization", "a7b857f6-........rest of my token")
                .get();

        System.out.println("status: " + response.getStatus());
        System.out.println("headers: " + response.getHeaders());
        System.out.println("body:" + response.readEntity(String.class));
}

Can you give me a hint if I missed something? It will be probably some dumb mistake but I spent several hours trying to make it work and I am clueless.

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is that you're including the query parameters as part of the path, and they're presumably being URL-encoded before passing to the server. Instead, set query parameters explicitly (which also makes it easier to use variables):

Response response = client
    .target("https://serverUrl")
    .path("/v1/search")
    .queryParam("q", "someQuery")
    .request("application/json")
    .header("Content-Type", "application/json")
    .header("authorization", "a7b857f6-........rest of my token")
    .get();

Note that it's often helpful to turn up server debugging to where it prints the actual URLs being requested and how it's interpreting them. This would have shown that the URL the server was seeing had something wrong with it.