I have a curl syntax in .sh file. I need to run the curl sytnax or curl command in Java replicating the same syntax, but I am facing problem in replicating the same.
$AUTH_OPTION="--basic -u testuser:testpwd"
$HTTP_METHOD=POST
$FILE_OPTION="-d @$INPUT_FILE"
$CONTENT_TYPE="application/xml"
$ACCEPT_TYPE="application/xml"
echo curl -o response.txt -w %{http_code} -k -v $AUTH_OPTION -X $HTTP_METHOD $FILE_OPTION -H \"Content-Type: $CONTENT_TYPE\" -H \"Accept: $ACCEPT_TYPE\"
I have the corresponding Java code as:
StringBuffer curlCmd=new StringBuffer();
curlCmd.append("curl -o response.txt");
curlCmd.append(WHITE_SPACE);
curlCmd.append("-w %{http_code}");
curlCmd.append("-k -v -u testuser:testpwd");
curlCmd.append(WHITE_SPACE);
curlCmd.append("-X POST");
curlCmd.append(WHITE_SPACE);
curlCmd.append("-d @/test/xyz/xml" );
curlCmd.append(WHITE_SPACE);
curlCmd.append("-H"+"Content-type: application/xml");
curlCmd.append(WHITE_SPACE);
curlCmd.append("-H"+" Accept: application/xml");
curlCmd.append(WHITE_SPACE);
This does not seems to work: its not simulating the same behaviour of .sh curl syntax. Can any one help me to sort out this issue?
output curl -o response.txt -w %{http_code} -k -v -u testuser:testpwd -X POST -d @/path/xyz.xml -H "Content-Type: app开发者_开发知识库lication/xml" -H "Accept: application/xml" the problem is xml is not getting accessed properly
I think there are a few possible problems, but one that catches my eye is that you are missing quotes around Content-Type: $CONTENT_TYPE
and Accept: $ACCEPT_TYPE
, for example:
"-H \"Content-type: application/xml\""
A second error is you have written -d @/test/xyz/xml
but it should be:
-d @/test/xyz.xml
If it still doesn't work, can you post the output of both the sh script and your StringBuffer so we can more easily see where the differences are?
If you're using environment variables then you need to make sure that:
- they are
exported
- you execute
curl
via a shell (e.g./bin/bash
)
The exporting means that the variables are exposed to child processes. The shell execution will expand these prior to calling your executable.
So your invocation will look like:
sh curl ....
It would help to see how you're invoking Process.exec().
One common gotcha is that you need to consume the stdout/stderr of the process concurrently, otherwise your sh/curl
process may block waiting for your parent process to consume the output. See here for more details.
You should probably replace Environment variables will not be interpolated by Java.%{http_code}
with something else on line 4 of the Java code.
Also, take a look at the Runtime#exec method. This lets you execute commands without having to worry about escaping quotes and such.
It's probably a good idea to make sure that your command runs without problems (such as the server not accepting the posted content) before trying to debug the invocation from java. It's far easier to deal with one problem at a time.
精彩评论