-
-
Save strongant/160d7a5a226cb1e0be5c9ec1cb212402 to your computer and use it in GitHub Desktop.
Sending post request with params and fetching response content
This file contains 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