Dean Blakely
Dean Blakely

Reputation: 3595

How to do an http post passing complex objects?

The code pasted below (from android snippets) is a typical example of how to do an http post passing a few simple parameters. The client is an Android client. This is typical of what I am able to find on the internet...

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
}

}

I need to pass more complex data. I want to do an http post passing a TripLocker_s object containing maybe 500 TriplegModel_s objects in it. The object's definition is pasted below...

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>();
}

How can I pass this object using HTTP POST? BTW, the service is an ASP.NET Web api service. Thanks, Gary

Upvotes: 1

Views: 1767

Answers (1)

Code Droid
Code Droid

Reputation: 10472

Convert to/from JSON. Thats the best way. http://code.google.com/p/google-gson/ Its fast as lightning.

Upvotes: 1

Related Questions