java使用params和Body生成HttpPost
我需要用Java复制一篇邮递员文章。 通常,我必须在URL中仅使用参数创建一个HttpPost,因此很容易构建:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
但是如果我有一篇像下图这样的帖子,URL和Body中都有参数,我该怎么办呢?? 现在我正在制作HttpPost,如下所示:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
HttpResponse httpResponse = client.execute(post);
//Do something
}catch (Exception e){
//Do something
}
但是我如何将“filename”和“filedata”参数与URL中的参数放在一起呢? 实际上我在用org。Apache库,但我也可以考虑其他库。
感谢所有愿意帮忙的人
# 1 楼答案
我决定这样做:
这里是代码
# 2 楼答案
我认为this问题和this问题都是关于类似的问题,并且都有很好的答案
我建议您使用this库,因为它维护良好,如果您愿意,使用起来也很简单
# 3 楼答案
您可以使用下面的代码在POST方法调用中以“application/x-www-form-urlencoded”的形式传递主体参数