如何使用java卷曲URL并将输出保存到文件

时间:2013-03-06 09:18:11

标签: java linux curl

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

让我们考虑一下,我在Linux机器上使用了以下的URL 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并点击网址时,我都需要根据parameter1作为文件名将输出写入新文件。

2 个答案:

答案 0 :(得分:1)

您是否必须使用Java的curl命令?你能用HttpClient获取html文件吗? http://hc.apache.org/httpclient-3.x/

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

答案 1 :(得分: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);
    }
}

}`