【问题标题】:Java using URLConnection to curl with --verbose switchJava 使用 URLConnection 通过 --verbose 开关卷曲
【发布时间】:2017-12-16 04:07:54
【问题描述】:

我正在尝试使用 java.net.URLConnection 发出 curl 请求。 但是,当使用 --verbose 开关执行时,我需要解析命令的输出。

以下代码按预期执行 curl 请求,我只是在寻找一种方法来获取命令的详细输出。

        String stringUrl = this.contUrl + "/auth?action=login";
        URL url = new URL(stringUrl);
        URLConnection uc = url.openConnection();

        System.out.println(stringUrl);
        System.out.println("Authorization: " + this.header);

        uc.setRequestProperty("X-Requested-With", "Curl");
        uc.setRequestProperty("Authorization", this.header);

        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String result = "";
        String line;    
        while((line = in.readLine()) != null) {
            result += line;
        }

【问题讨论】:

  • 您的问题是什么?什么是 --verbose 开关?
  • curl 是一个命令行工具。您不是在运行curl,而是在运行 Java 代码,因此不存在“卷曲请求”之类的东西。假设this.contUrl 的值以http: 开头,那么您正在发出“HTTP 请求”。如果您希望您的 Java 代码编写类似于 --verbosecurl 所做的输出,则由您编写代码以打印请求和响应标头,可通过调用 URLConnection 上的方法来访问。
  • @TuyenNguyen 请参阅 curl 手册页:curl.haxx.se/docs/manpage.html#-v
  • 谢谢安德烈亚斯。我很清楚我正在运行 Java 代码而不是命令行工具 curl。 “由您编写代码以打印请求和响应标头”正是我需要的正确方向。谢谢。

标签: java curl urlconnection verbose


【解决方案1】:

我有一个从命令行读取输出的功能,希望对您有所帮助:

private String readCommandOutput(String pattern) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(uc.getInputStream());
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    String charset = "utf-8";
    int result = bis.read();
    String output = "";
    String lineSeparator = System.getProperty("line.separator");
    while (result != -1) {
        buf.write((byte) result);
        output = buf.toString(charset);
        if (!output.equals(lineSeparator)) {
            String output_arr[] = output.split(lineSeparator);
            String lastLine = output_arr[output_arr.length - 1];

            // check if this is the end of stream and the pattern is match
            if (lastLine.endsWith(pattern) && bis.available() == 0) {
                return output;
            } 
        }           
        result = bis.read();
    }
    return buf.toString(charset);
}

我使用pattern 的这段代码是一个字符串,用于确定命令何时完成停止从流中读取的工作。我不知道你程序的输出是什么,你可以参考我的代码修改适合你的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2012-10-06
    • 1970-01-01
    • 2010-12-10
    • 2019-03-03
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多