URLConnection Post
In this chapter you will learn:
Post to URLConnection
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;
// j a v a2s . 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();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI