2016-04-26 79 views
1

我看到這個tutorial如何發送與JSON身體和網址參數http後?

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"); 

我想發送POST HTTP請求,在身體和網址參數

JSON如果我按照本教程中的例子,

會把第二setEntity覆蓋第一個setEntity

如果是的話,我該怎麼寫呢?

+0

這是什麼目的?你已經在第一個代碼中發送了「UrlEncodedFormEntity」,你不能發送任何json。所以是的,第二個''setEntity''覆蓋了第一個。 – f1sh

回答

2

setEntity只是設置當前實體,並不像setHeader方法那樣追加到它。

HTTP不允許發佈多個實體,這是您正在嘗試執行的操作。

我建議所有的數據編製成一個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

競猜httpPost是WebRequest的類型。

第二個setEntity會覆蓋第一個setEntity嗎?

是的,它會的。

使POST請求,你應該這樣做:

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;