In my case, a certain HTTP Request would work in curl within Git Bash on Windows. However, I would get a Connection Reset error when running on Java using HttpClient and HttpGet (org.apache.http.client.methods.HttpGet).
If I tried to use exec to directly run the command, for some reason it would not work.
As a workaround, this code will write the command in a batch file, then run the batch file and place the output in command.txt.
Here is the command which needs to be in the command.bat file (I have changed the endpoint and password):
"C:\Users\scottizu\AppData\Local\Programs\Git\bin\sh.exe" --login -i -c "curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt"
Here is the code (notice the command has special characters escaped):
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CURL_Runner {
public static void main (String[] args) throws Exception {
String command = "\"C:\\Users\\scottizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe\" --login -i -c \"curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt\"";
createAndExecuteBatchFile(command);
}
public static void createAndExecuteBatchFile(String command) throws Exception {
// Step 1: Write command in command.bat
File fileToUpload = new File("C:\\command.bat");
try {
if(fileToUpload.getParentFile() != null && !fileToUpload.exists()) {
fileToUpload.getParentFile().mkdirs();
}
FileWriter fw = new FileWriter(fileToUpload);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(command);
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
// Step 2: Execute command.bat
String[] cmdArray = new String[1];
cmdArray[0] = "C:\\command.bat";
Process process = Runtime.getRuntime().exec(cmdArray, null, new File("C:\\"));
int processComplete = process.waitFor();
}
}