Created
June 26, 2013 13:35
-
-
Save programaker/5867408 to your computer and use it in GitHub Desktop.
Sending post request with params and fetching response content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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