Skip to content

Instantly share code, notes, and snippets.

@jiafangtao
Created June 25, 2018 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiafangtao/d9a30d42a2d787fd83b300a77726dc9c to your computer and use it in GitHub Desktop.
Save jiafangtao/d9a30d42a2d787fd83b300a77726dc9c to your computer and use it in GitHub Desktop.
Invoke curl to do HTTP POST in JAVA
/*
* Sends a POST request to target URL by forking curl.
* Returns the response content on success; Otherwise returns null.
*
*/
private static String sendPostWithCurl (String url) {
String [] cmdOptions = new String[] {"/usr/bin/curl", "-k", "-H \"Content-Length: 0\"", "-X", "POST", url};
StringBuilder builder = new StringBuilder();
Process process;
try {
process = new ProcessBuilder(cmdOptions).start();
InputStream is = process.getInputStream();
InputStream es = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
//debugging
br = new BufferedReader(new InputStreamReader(es));
while ((line = br.readLine()) != null) {
System.out.println("Error: "+ line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment