Created
June 25, 2018 07:46
-
-
Save jiafangtao/d9a30d42a2d787fd83b300a77726dc9c to your computer and use it in GitHub Desktop.
Invoke curl to do HTTP POST in JAVA
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
/* | |
* 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