Convert Curl command into Java/Android

为君一笑 提交于 2020-01-05 14:04:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20782140/convert-curl-command-into-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!