从Java执行CURL – 什么是正确的方法?

我通过以下代码执行curl:

// execute process Process pr = null; Runtime run = Runtime.getRuntime(); try { pr = run.exec(cmdline.split(" ")); A ret = ff(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); } } 

但是,当我将以下内容添加到exec字符串中时:

在我将它传递给上面看到的方法之前,我正在构建curl字符串:

  if (userAgent.contains(" ")) { userAgent = " --user-agent '" + Exec.escapeShellString(userAgent) + "' "; } 

使用额外的单引号我得到:

 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)'" 

没有单引号,我得到这个:

 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)" 

有一个领先的单引号,但不是一个完成的。 我相信应该没有单引号..无论如何,java和curl之间有魔法……

我想做的就是传递一个这样的字符串:Opera / 9.25(Windows NT 6.0; U; en)

期待这个:

 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)" 

编辑:

我使用curl的原因是因为curl似乎是在200.301或302以外的任何响应上检索内容的唯一选项。

当你有一个名为Apache httpcleint的库来处理java中的这些东西时,我不知道你为什么要尝试使用java中的curl。

看看这个例子 。

或者,您也可以使用java的内置URLConnection或HttpURLConnection类来实现这些目的。

如果您来自PHP背景,并且如果您坚持使用cURL,请尝试使用libcurl Java绑定 。

你可以使用apache中的HttpClient发送你想要的所有必要的头文件:

  import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; public static void main(String[] args) throws HttpException, IOException { HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod("http://cetatenie.just.ro/Home/ORDINEANC.aspx"); getMethod.addRequestHeader("Host", "cetatenie.just.ro"); getMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"); httpClient.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(); } } 

这只是一个小例子。