来自Java的CURL中的Exec' - 正确的方法是什么?

时间:2012-02-03 05:37:14

标签: java shell curl exec

我正在通过以下代码执行curl:

  // 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);
        }
    }

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

我正在构建卷曲字符串,然后将其传递给上面显示的方法:

        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以外的任何响应中检索内容的唯一选项。

2 个答案:

答案 0 :(得分:2)

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

看看这个example

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

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

答案 1 :(得分:1)

您可以使用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(); 
   }
}

这只是一个小例子。