Skip to content

Instantly share code, notes, and snippets.

@ThunderWiring
Last active July 14, 2018 12:16
Show Gist options
  • Save ThunderWiring/307bb7dd4935a323dd70160916033f69 to your computer and use it in GitHub Desktop.
Save ThunderWiring/307bb7dd4935a323dd70160916033f69 to your computer and use it in GitHub Desktop.
connecting to an HTTP server and sending a POST request
HttpURLConnection urlConnection = null;
StringBuffer response = new StringBuffer();
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(5000);
// Send the post body
DataOutputStream wr = new DataOutputStream (urlConnection.getOutputStream());
wr.writeBytes(postData.toString());
wr.flush ();
wr.close ();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//Get Response
InputStream is = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
rd.close();
} else {
response.append("HTTP Response code not OK - " + urlConnection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return response.toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment