URLConnection.getOutputStream() has the following syntax.
public OutputStream getOutputStream() throws IOException
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; // w w w .ja va 2s . c om 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.