01: import java.io.BufferedReader;
02: import java.io.InputStream;
03: import java.io.InputStreamReader;
04: import java.io.IOException;
05: import java.io.OutputStream;
06: import java.io.PrintWriter;
07: import java.net.URL;
08: import java.net.URLConnection;
09: import java.net.URLEncoder;
10: 
11: /**
12:    This program posts a query to a United States Postal Service
13:    server that can look up the ZIP code for a city name. Supply
14:    the city name and an optional state on the command line, 
15:    such as 
16:    java PostZipQuery Los Angeles, CA
17: */
18: public class PostZipQuery
19: {  
20:    public static void main(String[] args) throws IOException
21:    {  
22:       // concatenate all command line arguments
23: 
24:       String input;
25:       if (args.length > 0)
26:       {
27:          input = args[0];
28:          for (int i = 1; i < args.length; i++)
29:             input += " " + args[i];
30:       }
31:       else
32:          input = "90210";
33: 
34:       // establish URL connection
35: 
36:       URL u = new URL(
37:          "http://www.usps.gov/cgi-bin/zip4/ctystzip");
38:       URLConnection connection = u.openConnection();
39:       
40:       // send POST data
41: 
42:       connection.setDoOutput(true);
43:       OutputStream out = connection.getOutputStream();
44:       PrintWriter writer = new PrintWriter(out);
45:       writer.print("ctystzip=" 
46:          + URLEncoder.encode(input) + "\n");
47:       writer.close();
48: 
49:       // print server response
50: 
51:       InputStream in = connection.getInputStream();
52:       BufferedReader reader = new BufferedReader(new
53:          InputStreamReader(in));
54: 
55:       boolean done = false;
56:       while (!done)
57:       {  
58:          String inputLine = reader.readLine();
59:          if (inputLine == null)
60:             done = true;
61:          else
62:             System.out.println(inputLine);
63:       }
64:       reader.close();
65:    }
66: }
67: