【问题标题】:How to curl an URL and saving output to a file using java如何使用 java 卷曲 URL 并将输出保存到文件
【发布时间】:2013-02-21 00:03:49
【问题描述】:

我是 java 新手,需要帮助了解如何在 java 中使用 cURL 并在运行时将 cURL 命令的输出保存到文件中。

让我们考虑一下,因为我正在使用下面的 URL,我必须在 linux 机器上 cURL

http://maniv.com/maniv/rest?method=sendMessage&msg_type=binary&parameter1=9999999&parameter2=9999999

当我在 linux 中使用curl "http://maniv.com/maniv/rest?method=sendMessage&msg_type=binary&parameter1=9999999&parameter2=9999999" 访问上述 URL 时,它会给出如下输出:

Message | sent | successfully

现在,当我更改 parameter1 并点击 URL 时,我每次都需要将输出写入基于 parameter1 作为文件名的新文件。

【问题讨论】:

  • 你试过什么?你的问题在哪里?
  • 到目前为止,我正在使用 shell 脚本执行此操作。但我需要在 java 中执行此操作并集成到 GUI 中。所以,请给出想法。

标签: java linux curl


【解决方案1】:

Java 必须使用 curl 命令吗?你可以使用 HttpClient 来获取 html 文件吗? http://hc.apache.org/httpclient-3.x/

请参考这个问题:Read url to string in few lines of java code。它提供了很好的答案。

【讨论】:

  • 一切都好..我只需要编写代码。因为,我是一个新手,我只需要 java 中的 HTTPcURL 的想法。
  • 此链接可能适合您:docs.oracle.com/javase/tutorial/networking/urls/readingURL.html。您只需要从 URL 读取 html 文件。
  • 老兄,我的不是静态 URL。 http://maniv.com/maniv/rest?method=sendMessage&msg_type=binary&**parameter1=9999999**&**parameter2=9999999**PARAMETERT1PARAMETER2 是用户输入。所以,在URL oracle = new URL("http://www.oracle.com/"); 我无法使用。
  • 您似乎正在尝试进行POST操作:stackoverflow.com/questions/3324717/…
【解决方案2】:

感谢您的努力。经过长时间的尝试,我得到了答案! `

    String url = "http://maniv.com/maniv/rest";
    String charset = "UTF-8";
    String method = "sendMessage";
    String msg_type = "binary";
    String parameter1 = "9999999";
    String parameter2 = "0000000";
    String msg = "001100110001100011";

    // ...
    StringBuffer sb = null;
    String query = String
            .format("method=%s&msg_type=%s&userid=%s&password=%s&msg=%s",
                    URLEncoder.encode(method, charset),
                    URLEncoder.encode(msg_type, charset),
                    URLEncoder.encode(userid, charset),
                    URLEncoder.encode(password, charset),
                    URLEncoder.encode(msg, charset));
    try {
        URL requestUrl = new URL(url + "?" + query);
        HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(query);
        osw.flush();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String in = "";
        sb = new StringBuffer();
        while ((in = br.readLine()) != null) {
            sb.append(in + "\n");
            System.out.println("Output:\n" +in);
        }
    } catch (Exception e) {
        System.out.println("Exception occured" + e);
    }
}

}`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2020-04-22
    • 2014-11-02
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多