I want to upload some data from an Android application to Pachube.
[Update: For people reading this in 2013, "Pachube" became "Cosm", which is now "Xively".]
This hurl is provided by their documentation as an example.
How can I achieve this with Android's implementation of HttpPut (or HttpPost)?
I don't really want to have to add any extra libraries, as I want to keep the application as small as possible.
I already have a JSONObject with my data in it.
Here is some pseudocode. Note that you shouldn't send form url encoded data in a PUT request, as it may break server side OAuth (if being used):
HttpClient client = new DefaultHttpClient();
HttpPut put = new HttpPut(url);
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
put.setEntity(new StringEntity(jsonObj.writeValue()));
HttpResponse response = client.execute(put);
One way to do this in Java / Android without any additional libraries is:
URL url = new URL("http://www.example.com/whatever");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.write("Data you want to put"); // for example your JSON object
out.close();
UPDATE - as per comments:
you can get the response for example by calling httpCon.getInputStream()
and/or httpCon.getErrorStream()
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.