下面粘貼的代碼(來自android片段)是一個典型的如何做一個http post傳遞幾個簡單參數的例子。客戶端是Android客戶端。這是典型的什麼我能在互聯網上找到...如何做一個http post傳遞複雜對象?
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/api/TripLocker");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
我需要通過更復雜的數據。我想做一個http post,傳遞一個包含500個TriplegModel_s對象的TripLocker_s對象。該對象的定義粘貼在...
public class TripLegModel_s
{
public string ourDirection; //SE, SW, SSW, etc.
public double longitude;
public double latitude;
public double altitude;
public DateTimeOffset TimeStamp;
public double speed;
}
public class TripLocker_s
{
public ObservableCollection<TripLegModel_s> BreadCrums = new ObservableCollection<TripLegModel_s>();
}
如何使用HTTP POST傳遞此對象?順便說一下,該服務是一個ASP.NET Web API服務。 謝謝,加里
Web服務接受哪種數據格式?無論它是哪種格式,都應該像這樣傳遞對象。 – MCeley
一種可能的選擇:單個名稱/值對:「myComplexObject」=> myCrossPlatformSerializedStringUrlEncoded。 IOW將整個對象序列化爲ASP.NET代碼可以理解的格式(即不是Java特定的),然後對其進行URL編碼並將結果作爲單個POST參數傳遞。序列化可以用JAXB替代方法完成(對於APK,JAXB太重了):http://stackoverflow.com/questions/1351218/unmarshalling-xml-files-into-java-objects-in-android。 –