Reputation: 213
Here's the curl command I'm attempting to replicate:
Below is the curl request.
curl user:password@localhost:8080/foo/bar -d property_one=value_one -d property_two=value_two -d property_three=value_three
And here is the code for httpurlconnection
URL thisurl = new URL ("http://localhost:8080/foo");
String encoding = Base64Encoder.base64Encode("user:password");
HttpURLConnection connection = (HttpURLConnection) thisurl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.addRequestProperty("property_one", "value_one");
connection.addRequestProperty("property_two", "value_two");
connection.addRequestProperty("property_three", "property_three");
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
On the connection.getInputStream() line I get a 401 error. Am I doing the authentication wrong?
Upvotes: 2
Views: 3631
Reputation: 311054
connection.setRequestMethod("GET");
Here you're setting the method to "GET", which is the same as you used with curl
.
connection.setDoOutput(true);
Here you are implicitly setting it to "POST", which isn't the same, so you don't have any reason to expect the same result.
Don't do all this authentication by hand. Use java.net.Authenticator.
That's what it's for.
Upvotes: 1
Reputation: 1061
401 error
because off user authentication.It may be possible that you are not encoding authentication header properly. use this code it worked for me.you can get detail here here
URL url = new URL ("http://localhost:8080/foo");
String encoding = org.apache.catalina.util.Base64.encode(credentials.getBytes("UTF-8"));
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
Upvotes: 1