Skip to content

Instantly share code, notes, and snippets.

@mrWinston
Last active October 24, 2022 09:10
Show Gist options
  • Save mrWinston/60b5cfe84afbee96e112 to your computer and use it in GitHub Desktop.
Save mrWinston/60b5cfe84afbee96e112 to your computer and use it in GitHub Desktop.
Send a Post Request #java #http #post #curl
/**
* Example taken from http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
*
**/
private static void sendPost() throws Exception {
String url = "https://www.sampleURL.example";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "someParameters=12&otherOne=parametrere";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
@newlifebeat
Copy link

Now this most likely does the job.
Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment