Created
March 24, 2013 17:36
-
-
Save ratpik/5232763 to your computer and use it in GitHub Desktop.
This describes a way to submit HTTP POST in a way the REST interface provided by Tastypie to Django understands it for JSON data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Creating the data to be sent, note the escaped quotes that are required | |
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); | |
nameValuePairs.add(new BasicNameValuePair("\A\"", "\"/api/v1/a/1/\"")); | |
nameValuePairs.add(new BasicNameValuePair("\"B\"", "\"/api/v1/b/1/\"")); | |
nameValuePairs.add(new BasicNameValuePair("\"C\"", "\"Hello from Android\"")); | |
//Create the client and set headers | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost(urlToPost); | |
httppost.setHeader("content-type", "application/json"); | |
//Setting the Authorization header | |
String encoded = "Basic " + Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP); | |
httppost.setHeader("Authorization",encoded); | |
//String the data and set it as HTTP Parameters in the POST request | |
StringEntity entity = new StringEntity(getQueryJSON(nameValuePairs)); | |
httppost.setEntity(entity); | |
HttpResponse response = httpclient.execute(httppost); | |
if(response!=null){ | |
InputStream in = response.getEntity().getContent(); //Get the data in the entity | |
readStream(in); | |
} | |
//Utility function to encode the JSON to string | |
private String getQueryJSON(List<NameValuePair> params) throws UnsupportedEncodingException | |
{ | |
StringBuilder result = new StringBuilder(); | |
boolean first = true; | |
for (NameValuePair pair : params) | |
{ | |
if (first){ | |
first = false; | |
result.append("{"); | |
}else | |
result.append(","); | |
result.append(pair.getName()); | |
result.append(":"); | |
result.append(pair.getValue()); | |
} | |
result.append("}"); | |
return result.toString(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome, thank you very much!