Friday, March 22, 2013

POSTing JSON to Tastypie from Android

Hello,

I'm unable to get the POST json to tastypie from an android http client to work.

I have tried with HttpURLConnection

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"), Base64.DEFAULT); 
urlConnection.setRequestProperty("Authorization", "Basic "+ new String(encoded, "UTF-8"));

JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
outputStreamWriter = urlConnection.getOutputStream();
outputStreamWriter.write(jsonObject.toString().getBytes());
outputStreamWriter.flush(); 
 

And I have tried with Apache HttpClient

HttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost(url);
        
post.setHeader("accept", "application/json");
post.addHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic "+ new String(encoded, "UTF-8"));


ArrayList localArrayList = new ArrayList();
localArrayList.add(new BasicNameValuePair("json",jsonObject.toString()));
      
 lotlisting.setEntity(new UrlEncodedFormEntity(localArrayList));
 String str = EntityUtils.toString(localDefaultHttpClient.execute(lotlisting).getEntity());

StringEntity se = new StringEntity( jsonObject.toString());  
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                
 post.setEntity(se);
                
 HttpResponse response = client.execute(post); 

I hit the same issue with both of them i.e the POST data as seen as Querydict in Django, does not have any data. This makes it an invalid json and it throws a JSON could not be decoded error.

I have tried playing with all the parameters with little luck. Note that get works perfectly, even with parameters. 

Has anyone been successfully able to post json from an android client to django/tastypie? If yes, could you please share what worked for you?

Thanks.

Pratik

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate