Java 如何使用 Apache HttpClient 发送 XML POST 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9848557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:32:43  来源:igfitidea点击:

How to send XML POST request using Apache HttpClient?

javahttp-postapache-commons-httpclient

提问by Dinesh

I want to do a HTTP POST of the format as follows,

我想做如下格式的 HTTP POST,

<?xml version="1.0" encoding="UTF-8" ?>
<authRequest>
 <username>someusernamehere</username>
 <password>somepasswordhere</password>
</authRequest>

I usually work with the following mechanism for any login based POST,

对于任何基于登录的 POST,我通常使用以下机制,

HttpParams params = new BasicHttpParams();
        params.setParameter(
                "http.useragent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        DefaultHttpClient httpclient = new DefaultHttpClient(params);

        HttpPost httppost = new HttpPost("http://mysite.com/login");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("username", "stackoverflow"));
        formparams.add(new BasicNameValuePair("password", "12345"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(entity);
        HttpResponse httpresponse = httpclient.execute(httppost);

But with this way, the POST data will be look like,

但是通过这种方式,POST 数据将如下所示,

username=stackoverflow&password=12345

How can I format this request as per the specified XML format that I mentioned above?

如何根据我上面提到的指定 XML 格式格式化此请求?

Thanks in advance.

提前致谢。

采纳答案by McDowell

Use a different kind of HttpEntity. There are a number of implementations listed at the top of the documentation.

使用不同类型的HttpEntity. 文档顶部列出了许多实现。