Skip to content

Instantly share code, notes, and snippets.

@dwivedi
Created August 13, 2015 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwivedi/8272d6ddadcf21be0d71 to your computer and use it in GitHub Desktop.
Save dwivedi/8272d6ddadcf21be0d71 to your computer and use it in GitHub Desktop.
public String postMethod(String conUrl, JSONObject nvps) throws Exception {
String result = null;
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
URI u = new URI(conUrl);
HttpPost httppost = new HttpPost(u);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 24000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Here add some Header Info if needed
httppost.setHeader("Content-Type", "application/json"); // to define content type in json
httppost.setHeader("Accept",
"application/json, text/javascript, */*;q=0.01"); // to accept in JSON in UTF8
// Here post Json String (In above httpPost object accept application/json in UTF8 format)
httppost.setEntity(new ByteArrayEntity(nvps.toString().getBytes("UTF8")));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
is = entity.getContent();
result = getStringfromInputStream(is);
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return result;
}
/**
Convert Input stream to String by using bufferd reader
Neha you should use volly api if you need.
*/
public String getStringfromInputStream(InputStream is) {
String result = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Helper.printStackTrace(e);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment