Working example POST in android

Here is another short (IMHO) example how to post in android app.

[java]
private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;

try {
url = new URL(“http://yourserver.com/sendsms”);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(“sms”, text));//POST param as “sms”

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, “UTF-8”));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + “:insert status=” + status);

} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
[/java]

This is a method for concatenating parameters for POST

[java]
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;

for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append(“&”);

result.append(URLEncoder.encode(pair.getName(), “UTF-8”));
result.append(“=”);
result.append(URLEncoder.encode(pair.getValue(), “UTF-8″));
}

return result.toString();
}[/java]

Do not forget about adding permission in manifest!
[java]<uses-permission android:name=”android.permission.INTERNET” />[/java]

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :