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

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

Below is the example for setting request headers
HttpPost post = new HttpPost("someurl");
post.addHeader(key1, value1));
post.addHeader(key2, value2));

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());

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

Related

Post with HttpClient returns Bad Request

I am using Java, Spring boot and Apache HttpClient to try send a post request. The documentation of the resource I am trying to reach can be found here:
https://docs.enotasgw.com.br/v2/reference#incluiralterar-empresa
Below is my code:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(incluirEmpresa);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
post.setHeader("Authorization", "Basic " + apiKey);
try {
StringEntity entity = new StringEntity(json);
//tried to add these two lines to see if they would fix the error, but it is the same
entity.setContentEncoding("application/json");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(json);
System.out.println("======================");
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(response.getStatusLine().getReasonPhrase() + " - " + response.getStatusLine().getReasonPhrase());
idEmpresa = response.getEntity().getContent().toString();
}
My response is 400 - Bad Request. On the interactive documentation link above, when I post my Json, I receive the error of duplicate entry, which is what I expect since the information I am sending is already on the database.
Since the interactive documentation returns the error of duplicate, I know the problem is not within my json format, but on my post request. The documentation have samples on C#, but not on Java, which is what I am using.
By the way, the json is variable is a string in case this is relevant.
Could someone try to point to me what is wrong with my post code?
Found out what I was missing.
After reviewing what was being sent to the API, i noticed the json was not in the expected format. So I did some research and found that, at least for my case, setting the headers with the content type was not enough, I also had to set the Entity that was being set to the HttpPost, to do that, i had to change this line of the code:
StringEntity entity = new StringEntity(json);
to this:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
After that change, the requests started to work as expected.

SharePoint 2010 REST Java authentication

I was happy to access SharePoint using PowerShell. It just picked -DefaultCredential and I didn't have to worry about that. That was for prototyping.
But my actual code is Java. Now I am not sure about this at all.
Even though I make REST calls, even SOAP would fail if I don't authenticate properly.
Method 1 : NTLM
Here the only thing I am not sure about is the workstation ID. I login using Citrix to a VM and there is an explicit Workstation ID. I use that.
Returns 401.
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://teams.host.com/_vti_bin/listdata.svc/");
NTCredentials credentials = new NTCredentials("user", 'pass', "workstation", "Domain");
client.getCredentialsProvider().setCredentials(new AuthScope("teams.host.com",80), credentials);
HttpResponse response = client.execute(request);
Method 2 : Basic authentication.
HttpGet request = new HttpGet("http://teams.host.com/_vti_bin/listdata.svc/");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpResponse response = httpClient.execute(request);
Returns 401.
What other method do I use ? Digest ? Since I don't know how -DefaultCredential in PowerShell worked I am back to the drawing board.
How should I investigate this ? I must be making some basic mistakes in this Java code. The flow is not right. That is my supposition.
So from Apache HttpClient this is the code that connects to SharePoint 2010. The workstation ID is the one used when I use Citrix XenDesktop to login to a Windows machine. I am able to get the result of my REST Get request.
This uses NTLM authentication.
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://teams.host.com/_vti_bin/listdata.svc/");
NTCredentials credentials = new NTCredentials("user", 'pass', "workstation", "Domain");
client.getCredentialsProvider().setCredentials(new AuthScope("teams.host.com",80), credentials);
HttpResponse response = client.execute(request);

apache commons httpclient 4.23 form login problems different session cookies used in different requests

I have a protected resource which requires me to login. Im using the commons client with the following code block.
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.getParams().setParameter("http.protocol.single-cookie-header", Boolean.TRUE);
PostMethod postMethod = new PostMethod("/admin/adminlogon.do");
postMethod.setRequestEntity(new StringRequestEntity("action=logon&adminUser=admin&adminPassword=password",
"application/x-www-form-urlencoded",
"UTF-8"));
postMethod.addParameter("action","logon");
postMethod.addParameter("adminUser","admin");
postMethod.addParameter("adminPassword","password");
httpClient.executeMethod(postMethod);
String response2 = postMethod.getResponseBodyAsString();
Above is where I basically login. This works fine im getting a nice little JSESSIONID cookie back.
GetMethod get = new GetMethod("/admin/api.do?action=getSomeJson");
httpClient.executeMethod(get);
When I check the logic on the sever the for the 2nd request I notice that we are using a different JSESSIONID. Therefore the get seems to fail to log in. I was under the impression the httpClient managed the cookies and sent the same cookie back. When I log into my app normally through the UI I see the same cookie in each request just not in the this test code.
String s = get.getResponseBodyAsString();
get.releaseConnection();
Do I need to do something with the httpClient to ensure it uses the same cookies from the first post request when it does its get request??
Thanks in advance.
Your assumption regarding HTTP client cookie behavior is correct.
In your case your not use the same httpClient instance. To fix it you need to allocate the httpClient only once (in PostConstructor):
httpClient = new DefaultHttpClient(); // or new HttpClient();
Then, you perform your calls using the same instance of the client. The client will take a cookie from a response, will store it in the cookieStore and will send it with the next request.
[Added after the comment]
The following code works for me:
httpClient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);

Query parameters sent with HttpPut Request not being read properly

I am trying make an HttpPut Request to the server and send some parameters with it, but however I think that the parameters are not being detected due to which the server send an error message.
My Code is:
URI url = new URI("http://myurl.com/something/something");
HttpClient client = new DefaultHttpClient();
HttpPut hput = new HttpPut(utl);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("id",URLEncoder.encode(ppid,"UTF-8")));
pairs.add(new BasicNameValuePair("name",URLEncoder.encode(netid,"UTF-8")));
hput.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse res = client.execute(hput);
System.out.println(res.getStatusLine);
It says, the PUT method is not supported by the server but the server does support it.
Tried to do a lot research but wasn't successful as most of the posts were just for POST and GET.
Any help would be greatly appreciated.
Thanks.
Most of the servers PUT and DELETE methods are disabled default. Only GET/POST are enabled.

Sending post request from a servlet

I have been trying to send a POST request from a servlet and the code that I wrote is this:
HttpPost post = new HttpPost(url.build());
post.setEntity(new UrlEncodedFormEntity(nameValue));
post.setHeader("content-type", "application/json");
HttpClient client = new DefaultHttpClient();
HttpResponse res = client.execute(post);
The URL is "https://accounts.google.com/o/oauth2/token" and I send some parameters with this request.
However, when I run this I get AccessControlException.
The HttpPost method that I use here comes from org.apache.http i.e., commons HttpClient API. I have tried a lot but it doesn't seem to work.
So the question is "Is it possible to send a cross domain request using HttpClient?"

Categories

Resources