如何做一个传递复杂对象的http帖子?

时间:2012-09-21 19:45:17

标签: android http-post asp.net-web-api

下面粘贴的代码(来自android snippets)是一个典型的例子,说明如何通过一些简单的参数来传递http帖子。客户端是Android客户端。这是我能在互联网上找到的典型内容......

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&lt;NameValuePair&gt;(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帖子传递一个TripLocker_s对象,其中包含可能有500个TriplegModel_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服务。 谢谢,加里

1 个答案:

答案 0 :(得分:1)

转换为/从JSON转换。这是最好的方式。 http://code.google.com/p/google-gson/它像闪电一样快。