Java 如何使用apache commons HttpPost发送文件并对请求的参数进行编码?
我目前正在编写一个需要向服务器发送http Post请求的应用程序。请求需要包含特定参数,在等效GET请求中,这些参数将被编码到url中。但是,http请求的主体需要正确格式化xml,服务器将对其进行解析。因此,据我所知,文件需要添加到请求中,如下所示:Java 如何使用apache commons HttpPost发送文件并对请求的参数进行编码?,java,android,apache,http,post,Java,Android,Apache,Http,Post,我目前正在编写一个需要向服务器发送http Post请求的应用程序。请求需要包含特定参数,在等效GET请求中,这些参数将被编码到url中。但是,http请求的主体需要正确格式化xml,服务器将对其进行解析。因此,据我所知,文件需要添加到请求中,如下所示: httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("url..."); if (httpContent != null){ In
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));
List name-valuepairs=new-ArrayList(2);
添加(新的BasicNameValuePair(“userid”,“12312”);
添加(新的BasicNameValuePair(“sessionid”,“234”);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
现在,我非常确定httpPost只能有一个实体集,除非我误解了它。那么,如何设置参数并仍然保留xml作为http主体呢
提前谢谢 不要使用
UrlEncodedFormEntity
-这仍然是一个表单实体,不会提供您正在寻找的“GET请求”等价物
相反,只需将参数附加到传递给HttpPost
构造函数的URL上:
url...?userid=12312&sessionid=234
我需要像常规POST请求一样将参数编码到http主体中。我不想构造一个GET请求。问题是我不知道如何对参数进行编码并包含xml文件。@Mozoby-我们需要更好地了解您提交的服务器需要什么。如果上述方法不起作用,您可能需要使用
UrlEncodedFormEntity
,并将所有XML作为一个给定名称的值包含在内。这是正确的,我需要将参数编码为GET参数,并将XML放在帖子正文中。