hunterp
hunterp

Reputation: 15986

How to set Username in http post in java?

the http://username:[email protected] syntax does not seem to work with org.apache.http.impl.client.DefaultHttpClient I'm doing a POST

ideas?

Upvotes: 1

Views: 4266

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128899

Apache HTTP client has built-in support for authentication. Use that instead of trying to embed it in the URL. There is sample code for doing Basic auth on its examples page

Upvotes: 1

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

The http://username:[email protected] syntax is syntactic sugar that browsers implement to let the user provide credentials for HTTP BASIC. It is not part of the URL syntax.

Under the hood, this is translated to to a request to http://whatever.com with a special header called Authorization which contains the username and password coded with Base64. This is how the HTTP specification specifies it. It doesn't matter whether it is a GET or a POST request.

In order to use the apache client you must do exactly that. You can encode the header using the Base64 class of Apache Commons, and the format is expected to be username + ":" + password as the value, so something along the lines of:

Base64.encodeBase64String(String.format(%s:%s,username,password).getBytes());

See also Wikipedia for a more thorough explanation of the headers.

Upvotes: 2

Related Questions