簡體   English   中英

在Android中使用HttpPost發送對象數組

[英]Send Array of objects using HttpPost in Android

我有一個通過HttpPost將對象發送到api的應用程序。 我有一些示例:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Destination", destination));
nameValuePairs.add(new BasicNameValuePair("Description", description));
nameValuePairs.add(new BasicNameValuePair("CreatorName ", myName));

在此對象中,我有一個“用戶”對象數組,其中有一個DisplayName和Phone。 如何通過HttpPost發送此數組? 服務器無法識別以下內容(引號被轉義):

nameValuePairs.add(new BasicNameValuePair(“ Users”,“ [{” Destination“:” St.Louis“,” Phone“:” 1234“}]”)));

最簡單的方法是將Array轉換為String(或JSON字符串)。 作為實體傳遞后,然后使用服務器對其進行編碼。

嘗試這個

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);

StringEntity se = new StringEntity(nameValuePairs.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);

我認為這段代碼應該工作。

nameValuePairs.add(new BasicNameValuePair("user[0]", gson.toJson(users.get(0))));
nameValuePairs.add(new BasicNameValuePair("user[1]", gson.toJson(users.get(1))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM