我目前正在编写一个需要向服务器发送 HTTP Post 请求的应用程序。该请求需要包含特定参数,这些参数在等效的 GET 请求中将被编码在 url 中。但是,http 请求的主体需要是服务器将解析的正确格式的 xml。因此,据我了解,需要像这样将文件添加到请求中:
httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("url...");
if (httpContent != null){
InputStreamEntity httpStream = new InputStreamEntity(httpContent,-1);
httpStream.setContentType("text/xml");
httpStream.setChunked(true);
post.setEntity(httpStream);
}
并且需要像这样将参数添加为名称-值对:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "12312"));
nameValuePairs.add(new BasicNameValuePair("sessionid", "234"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
现在,我很确定 httpPost 只能有一个实体集,除非我误解了它。那么,如何设置参数并仍然保留 xml 作为 http 主体?
提前致谢!
最佳答案
不要使用 UrlEncodedFormEntity
- 这仍然是一个表单实体,不会为您提供您正在寻找的等效“GET 请求”。
相反,只需将您的参数附加到传递给 HttpPost
构造函数的 URL 上:
url...?userid=12312&sessionid=234
关于java - 我如何使用 apache commons HttpPost 发送文件并对请求的参数进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8691456/