Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTTP Request Header "authentication" using HTTPClient?

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

like image 615
user855 Avatar asked Oct 21 '10 01:10

user855


People also ask

How do I authenticate using HttpClient?

Clients can authenticate via username and password. These credentials are sent in the Authorization HTTP header in a specific format. It begins with the Basic keyword, followed by a base64-encoded value of username:password.

How do I set HttpClient credentials?

You can set the required credentials to the CredentialsProvider object using the setCredentials() method. AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. Credentials object − Specifying the credentials (username, password).

How do I add Authorization header in GET request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.


2 Answers

Below is the example for setting request headers

    HttpPost post = new HttpPost("someurl");

    post.addHeader(key1, value1));
    post.addHeader(key2, value2));
like image 98
Fahad Avatar answered Sep 17 '22 00:09

Fahad


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());
like image 21
Francisco Corrales Morales Avatar answered Sep 18 '22 00:09

Francisco Corrales Morales