1

I am developing two applications -

First one is web application using Spring MVC 3

And the second one is an Android application for same web application.

In both, I am integrating basic authentication to authenticate user on that site using the APIs.

In the API tutorial, following curl command is given to authenticate user -

$ curl -u username:password insert_Url_here -d '[xml body here]'

I am not getting, how to convert this command in Java and android code.

Please guide me. I am totally stuck here.

StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
Manoj Agarwal
  • 703
  • 3
  • 17
  • 39

1 Answers1

2

Using HttpClient 4, you will need to do the following:

  • create the client:

CloseableHttpClient client = HttpClientBuilder.create().build();

  • create the POST Request:

final HttpPost postRequest = new HttpPost(SAMPLE_URL);

  • set the body of your POST request:

request.setEntity(new StringEntity("the body of the POST"));

  • configure authentication (presumably Basic Auth):

UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

postRequest.addHeader(new BasicScheme().authenticate(creds, request, null));

That's it - this is essentially what your curl command does.

Hope this helps.

Community
  • 1
  • 1
Eugen
  • 8,523
  • 8
  • 52
  • 74
  • Thanks @Eugen. This is working fine for me. But authenticate method (new BasicScheme().authenticate(creds, request, null)) is deprecated. Can you provide any other approach too ? – Manoj Agarwal Dec 27 '13 at 05:01
  • Did you copy the line exactly as it is now (including the last null argument)? I'm using the latest httpclient version (4.3.1) and it is not deprecated - it's likely that you didn't include the last argument. – Eugen Dec 29 '13 at 17:27