开发者

How to set Username in http post in java?

the http://use开发者_C百科rname:password@whatever.com syntax does not seem to work with org.apache.http.impl.client.DefaultHttpClient I'm doing a POST

ideas?


The http://username:password@whatever.com 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜