3

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

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

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

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

Message | sent | successfully

现在,当我更改并点击 URLparameter1时,我每次都需要根据 as 文件名将输出写入一个新文件。parameter1

4

2 回答 2

1

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

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

于 2013-03-06T09:37:31.957 回答
1

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

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

}`

于 2013-03-07T06:51:49.323 回答