Java URLConnection .getOutputStream ()

Syntax

URLConnection.getOutputStream() has the following syntax.

public OutputStream getOutputStream()    throws IOException

Example

The following code posts values to a URL with URLConnection. It creates a URL first and open connection to that URL. Then it calls the set the output to true using setDoOutput. After that it posts to the URL by writing to the OutputStreamWriter.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
/*from  w  w  w. j  a v  a  2 s. co m*/
public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write("value=1&anotherValue=1");
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.net »




CookieManager
CookiePolicy
CookieStore
DatagramPacket
DatagramSocket
HttpCookie
HttpURLConnection
InetAddress
JarURLConnection
MulticastSocket
ServerSocket
Socket
SocketAddress
URI
URL
URLConnection
URLDecoder
URLEncoder