How to set HTTP Request Header “authentication” us

2019-05-11 07:02发布

I want to set the HTTP Request header "Authorization" when sending a POST request to a server. How do I do it in Java? Does HttpClient have any support for it?

http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z9

The server requires me to set some specific value for the authorization field: of the form ID:signature which they will then use to authenticate the request.

Thanks Ajay

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-11 07:34

Below is the example for setting request headers

    HttpPost post = new HttpPost("someurl");

    post.addHeader(key1, value1));
    post.addHeader(key2, value2));
查看更多
欢心
3楼-- · 2019-05-11 07:52

Here is the code for a Basic Access Authentication:

HttpPost request = new HttpPost("http://example.com/auth");
request.addHeader("Authorization", "Basic ThisIsJustAnExample");

And then just an example of how to execute it:

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpClient httpclient = null;
httpclient = new DefaultHttpClient(httpParams);

HttpResponse response = httpclient.execute(request);

Log.d("Log------------", "Status Code: " + response.getStatusLine().getStatusCode());
查看更多
可以哭但决不认输i
4楼-- · 2019-05-11 07:54

This question is "answered" here: Http Basic Authentication in Java using HttpClient?

There are many ways to do this. It was frustrating for me to try to find the answer. I found that the best was the Apache docs for HttpClient. Note: answers will change over time as the libraries used will have deprecated methods. http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/authentication.html

查看更多
登录 后发表回答