java 执行curl,从Java执行CURL - 什么是正确的方法?

博主在Java中使用Runtime.exec()方法执行curl命令时遇到问题,当添加用户代理字符串时,curl命令的参数被错误地转义,导致请求头不正确。尝试了在字符串中添加额外的单引号来解决,但结果仍有误。解决方案是使用Apache HttpClient或其他内置Java类来代替curl执行HTTP请求,避免直接调用外部进程。
摘要由CSDN通过智能技术生成

I am executing curl via the following code:

// execute process

Process pr = null;

Runtime run = Runtime.getRuntime();

try {

pr = run.exec(cmdline.split(" "));

A ret = f.f(pr);

pr.waitFor();

return ret;

} catch (Exception ex) {

throw new RuntimeException("Executing " + cmdline, ex);

} finally {

try {

// close all those bloody streams

pr.getErrorStream().close();

pr.getInputStream().close();

pr.getOutputStream().close();

} catch (IOException ex) {

Log.get().exception(Log.Level.Error, "Closing stream: ", ex);

}

}

However, when I add the following into the exec string:

I am building the curl string as I go, before I pass it to the method seen above:

if (userAgent.contains(" ")) {

userAgent = " --user-agent '" + Exec.escapeShellString(userAgent) + "' ";

}

With the extra single quotes I get this:

113.30.31.137 - - [03/Feb/2012:05:26:39 +0000] "GET / HTTP/1.1" 200 6781 "-" "'Mozilla/5.0(iPad;U;CPUOS3_2_1)'"

Without the single quotes, I get this:

107.21.172.36 - - [03/Feb/2012:05:33:38 +0000] "GET / HTTP/1.1" 200 6781 "-" "'Mozilla/5.0(iPad;U;CPUOS3_2_1)"

There is a leading single quote, but not a finishing one. I believe that there should be no single quotes.. anyhow, there is magic somewhere between java and curl...

All I would like to do is pass a string like this:

Opera/9.25 (Windows NT 6.0; U; en)

and expect this:

107.21.172.36 - - [03/Feb/2012:05:33:38 +0000] "GET / HTTP/1.1" 200 6781 "-" "Opera/9.25 (Windows NT 6.0; U; en)"

Edit:

The reason I am using curl is because curl seems to be the only option that retrieves the content on any response other than 200.301 or 302.

解决方案

I don't know why you are trying to use curl from java when you have a library called Apache httpcleint to handle these things in java.

Take a look at this example.

Alternatively you can also use java's inbuilt URLConnection or HttpURLConnection class for these purposes.

If you are from a PHP background and if you insist on using cURL try libcurl Java bindings.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值