【问题标题】:Exec'ing CURL from Java - whats the proper way?从 Java 执行 CURL - 什么是正确的方法?
【发布时间】:2012-02-25 19:21:20
【问题描述】:

我正在通过以下代码执行 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 字符串中时:

我正在构建 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 以外的任何响应上检索内容的唯一选项。

【问题讨论】:

    标签: java shell curl exec


    【解决方案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(); 
       }
    }
    

    这只是一个小例子。

    【讨论】:

      【解决方案2】:

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

      看看这个example

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

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

      【讨论】:

      • 我使用 curl 的原因是因为 curl 似乎是在 200.301 或 302 以外的任何响应中检索内容的唯一选项。
      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多