Tony
Tony

Reputation: 3638

Java HttpUrlConnection - 401 with authentication headers

Chances are I'm doing something wrong, but using a Curl/Rest client I'm able to send a http request to a server using an Oauth2 generated token, here's the details:

url: https://blah.blah
Authorization: OAuth <oauth token>
Accept: application/blah (I'm hiding some of the details...)

This works fine using Curl/Rest and I'm getting back a JSON object as expected. However, when doing this in Java, I'm getting a 401 every time. I'm guessing I'm messing up appending the headers somehow, but I can't see how.

url = new URL(baseUrl+ reqUrl);
    System.out.println("Querying API with the following url:" + url.toString());

    httpReq = (HttpURLConnection) url.openConnection();
    httpReq.addRequestProperty("Authorization: OAuth ", token.trim());
    httpReq.addRequestProperty("Accept", "application/blah...");
    httpReq.connect();

I'm guessing I'm getting the header set up wrong, but I can't see how. Is there a better way to implement the headers to the http request?

Any input or advice would be greatly appreciated. Thanks

Upvotes: 2

Views: 2046

Answers (2)

Morey
Morey

Reputation: 629

Do not include "OAuth" in the key specification of either addRequestProperty() or setRequestProperty(). So this is incorrect:

httpReq.addRequestProperty("Authorization: OAuth ", token.trim()); 

Instead it should be a part of the value:

String header = "OAuth oauth_token=\"ConsumerKey%3D...\",oauth_consumer_key=\"...";
httpReq.setRequestProperty("Authorization", header);

The above should work.

Upvotes: 0

himanshu
himanshu

Reputation: 144

You are setting Authorization: OAuth in curl while in code I see you are doing Authorization: I see OAuth missing, I hope this is not an issue.

Upvotes: 1

Related Questions