简体   繁体   中英

Java Jersey HTTPS GET request with Authentication header

I'm trying to integrate a payment service 'Mollie' ( http://www.mollie.nl ) which works over HTTPS requests into a Java environment.

As for this posts i'll be using following request to explain: Within PHP (since I have a PHP background) I can work with cURL:

$ curl -X GET https://api.mollie.nl/v1/methods \
-H "Authorization: Bearer API-KEY"

Which has a response:

在此输入图像描述

Testing the REQUEST from DHC (or Postman) return correct response.

在此输入图像描述

So within Java i'm using the Jersey library to try to access the Request:

    Client client = Client.create();
    WebResource webResource =   client.resource("https://api.mollie.nl/v1/methods");
    webResource.header("Authorization", "Bearer API-KEY");
    ClientResponse response = webResource    
            .header("Content-Type", "application/json;charset=UTF-8")
            .type("application/json")
            .accept("application/json")
            .get(ClientResponse.class);

    int statusCode = response.getStatus();
    if (statusCode == 401) {
        throw new AuthenticationException("Invalid Username or Password");
    }

    String responseCall = response.getEntity(String.class);

When executing the Java code the request throws a ClientHandlerException:

HTTP Status 500 - com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection timed out: connect

I'm running the Java test from a Apache localhost server. But I can't figure out why the Java request gives a timeout since the authentication header seems to be set correct (at least to me).

What I did notice is when visiting the path of the request https://api.mollie.nl/v1/methods it shows a pop-up for authentication.

It would be nice to get some usefull tips or information about this issue. Am I missing something?

Thanks!

Given all is is working correctly (I'm not sure why it would cause a timeout), one thing I see wrong is your usage of

webResource.header("Authorization", "Bearer API-KEY");

header returns an WebResource.Builder , and does not add the header to the current WebResource . So the request you are sending doesn't have the header. You can check it by adding a LoggingFilter

client.addFilter(new com.sun.jersey.api.client.filter.LoggingFilter(System.out));

You can fix this by doing

ClientResponse response = webResource
        .header("Authorization", "Bearer API-KEY");    
        .header("Content-Type", "application/json;charset=UTF-8")

Just moving the header to the method chaining.

I have resolved above issue. Apparently the work PROXY server was blocking outgoing HTTPS requests. Testing from a non-proxy environment fixed the issue. Thanks for all advice!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM