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

时间:2012-03-24 02:12:49

标签: java http-post apache-commons-httpclient

我想按照以下格式进行HTTP POST,

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

我通常使用以下机制进行任何基于登录的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);

但是通过这种方式,POST数据看起来像,

username=stackoverflow&password=12345

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

提前致谢。

1 个答案:

答案 0 :(得分:5)

使用其他类型的HttpEntitythe documentation顶部列出了许多实现。