Skip to content

Instantly share code, notes, and snippets.

@programaker
Created June 26, 2013 13:35
Show Gist options
  • Save programaker/5867408 to your computer and use it in GitHub Desktop.
Save programaker/5867408 to your computer and use it in GitHub Desktop.
Sending post request with params and fetching response content
public static String post(String urlString, String params, int timeout) throws Exception {
String response = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(params);
dos.flush();
is = conn.getInputStream();
Scanner s = new Scanner(is).useDelimiter("\\A");
response = s.hasNext() ? s.next() : null;
} finally {
if (dos != null) {
dos.close();
}
if (is != null) {
is.close();
}
if (conn != null) {
conn.disconnect();
}
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment