Ilkar
Ilkar

Reputation: 2177

How can I send POST data through url.openStream()?

i'm looking for tutorial or quick example, how i can send POST data throw openStream.

My code is:

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

Could you help me ?

Upvotes: 1

Views: 5000

Answers (3)

AlexR
AlexR

Reputation: 115378

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

Upvotes: 8

jere
jere

Reputation: 4304

Apache HTTP Components in particular, the Client would be the best way to go. It absracts a lot of that nasty coding you would normally have to do by hand

Upvotes: 0

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12222

Use Apache HTTP Compoennts http://hc.apache.org/httpcomponents-client-ga/

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

Look for HttpPost - there are some examples of sending dynamic data, text, files and form data.

Upvotes: 1

Related Questions