Reputation: 9568
I am creating a HTTPUrlConnection in android and preparing it for a post as shown below
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("content-type", "application/json");
byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"), Base64.DEFAULT);
//Basic Authorization
urlConnection.setRequestProperty("Authorization", "Basic "+ new String(encoded, "UTF-8"));
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//This gets implicitly set when DoOutput is True, but still let it be
urlConnection.setRequestMethod("POST");
//Required for POST not to return 404 when used on with a host:port combination
//http://stackoverflow.com/questions/5379247/filenotfoundexception-while-getting-the-inputstream-object-from-httpurlconnectio
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0");
urlConnection.setRequestProperty("Accept","*/*");
Then I prepare the JSON and write it to the OutputStream
of the connection
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
outputStreamWriter = urlConnection.getOutputStream ();
outputStreamWriter.write(jsonObject.toString().getBytes());
finally {
if (outputStreamWriter != null) try { outputStreamWriter.close(); } catch (IOException logOrIgnore) {}
}
When I do the request, I get a status of 500 because my server receives an empty POST data which is invalid json.
The same works from a web browser and curl. GET works on android with same parameters. What am I missing? Is something wrong with the ordering of the way parameters should be set for the POST request?
Upvotes: 2
Views: 3470
Reputation: 9568
I was able to get this to work. Snippets from code below
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 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();
}
Upvotes: 1