如何通过url.openStream()发送POST数据?

时间:2012-01-10 14:04:59

标签: java

我正在寻找教程或快速示例,我如何发送POST数据抛出openStream。

我的代码是:

  

URL url = new URL("http://localhost:8080/test");
            InputStream response = url.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));

你能帮帮我吗?

3 个答案:

答案 0 :(得分:5)

    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    // important: get output stream before input stream
    OutputStream out = connection.getOutputStream();
    out.write(content);
    out.close();        

            // now you can get input stream and read.
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {
        writer.println(line);
    }

答案 1 :(得分:1)

使用Apache HTTP组件http://hc.apache.org/httpcomponents-client-ga/

教程:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

寻找HttpPost - 有一些发送动态数据,文本,文件和表单数据的例子。

答案 2 :(得分:0)

特别是{p> Apache HTTP ComponentsClient将是最好的方式。 它抽象了很多你通常不得不手工编写的令人讨厌的编码