U5.java
import java.net.*;
import java.io.*;
import java.util.*; // for Map, Iterator, etc.
/**
Demonstration of URLConnection with POST and arguments.
*/
public class U5
{
public static void main(String argv[])
{
String line;
try {
// Step 1: Get a URLConnection.
String query = "http://leipold:80/cgi-bin/echo.pl";
String args = "this=that&black=white";
URL url = new URL(query);
URLConnection conn = url.openConnection();
// Step 2: Set its request properties.
conn.setDoInput(true); // This is the default.
conn.setDoOutput(true); // Makes this a POST.
// Step 2a: Write the POST data.
PrintWriter out =
new PrintWriter(conn.getOutputStream());
out.print(args);
out.close();
// Step 3: Connect to the remote resource.
conn.connect();
// Step 4: Examine returned header information.
System.out.println("Headers:");
Set headers = conn.getHeaderFields().entrySet();
Iterator iter = headers.iterator();
while (iter.hasNext()) {
Map.Entry z = (Map.Entry)(iter.next());
System.out.println(" " +
z.getKey() + " = " + z.getValue());
}
System.out.println();
// Step 5: Read the resource data.
InputStream in = conn.getInputStream();
BufferedReader reader =
new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}