将 Curl 命令转换为 Java/Android [英] Convert Curl command into Java/Android
问题描述
我正在开发两个应用程序 -
I am developing two applications -
第一个是使用 Spring MVC 3 的 Web 应用程序
First one is web application using Spring MVC 3
第二个是用于同一网络应用程序的 Android 应用程序.
And the second one is an Android application for same web application.
在这两种情况下,我都集成了基本身份验证以使用 API 对该站点上的用户进行身份验证.
In both, I am integrating basic authentication to authenticate user on that site using the APIs.
在API教程中,给出了以下curl命令来验证用户-
In the API tutorial, following curl command is given to authenticate user -
$ curl -u 用户名:密码 insert_Url_here -d '[xml body here]'
我不明白,如何在 Java 和 android 代码中转换此命令.
I am not getting, how to convert this command in Java and android code.
请指导我.我完全被困在这里.
Please guide me. I am totally stuck here.
推荐答案
使用 HttpClient 4,您需要执行以下操作:
Using HttpClient 4, you will need to do the following:
- 创建客户端:
CloseableHttpClient 客户端 = HttpClientBuilder.create().build();
CloseableHttpClient client = HttpClientBuilder.create().build();
- 创建 POST 请求:
- 设置 POST 请求的正文:
- 配置身份验证(大概是基本身份验证):
final HttpPost postRequest = new HttpPost(SAMPLE_URL);
final HttpPost postRequest = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity(POST 的正文"));
request.setEntity(new StringEntity("the body of the POST"));
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
postRequest.addHeader(new BasicScheme().authenticate(creds, request, null));
postRequest.addHeader(new BasicScheme().authenticate(creds, request, null));
就是这样 - 这基本上就是您的 curl
命令所做的.
That's it - this is essentially what your curl
command does.
希望这会有所帮助.
这篇关于将 Curl 命令转换为 Java/Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!