如何用json body和url params发送http帖子?

时间:2016-04-26 09:34:47

标签: java json http post

我看到了tutorial

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "John"));
params.add(new BasicNameValuePair("password", "pass"));
httpPost.setEntity(new UrlEncodedFormEntity(params));

String json = "{"id":1,"name":"John"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

我想在正文和url params

中发送带有json的POST http请求

如果我按照教程中的示例进行操作,

第二个setEntity会覆盖第一个setEntity吗?

如果是的话,我应该怎么写呢?

2 个答案:

答案 0 :(得分:2)

setEntity只设置当前实体,而不像setHeader方法那样追加到它。

HTTP不允许POST多个实体,这正是您要做的事情。

我建议将所有数据编译成一个JSON StringEntity,然后发送,或者只是将所有内容添加到UrlEncodedFormEntity

String json = "{"username":"John", "password":"pass", "id":1, "name":"John"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity)
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "John"));
params.add(new BasicNameValuePair("password", "pass"));
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "John"));
httpPost.setEntity(new UrlEncodedFormEntity(params);

答案 1 :(得分:-1)

猜猜httpPost是一种WebRequest类型。

  

第二个setEntity会覆盖第一个setEntity吗?

是的,它会。

要发布帖子请求,您应该这样做:

httpPost.Method = "POST";

要在正文中设置Json对象,请查看对this SO question的回复。

string serializedObject = Newtonsoft.Json.JsonConvert.SerializeObject(entity);

using (var writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(serializedObject);
}
var response = request.GetResponse() as HttpWebResponse;