The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.net  [27 examples] > URLs  [8 examples]

e135. Sending a POST Request Using a URL

See also e1071 Sending a POST Request Using a Socket.
    try {
        // Construct data
        String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
        data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
    
        // Send data
        URL url = new URL("http://hostname:80/cgi");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
    
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            // Process line...
        }
        wr.close();
        rd.close();
    } catch (Exception e) {
    }

 Related Examples
e132. Creating a URL
e133. Converting Between a URL and a URI
e134. Parsing a URL
e136. Getting Text from a URL
e137. Getting an Image from a URL
e138. Getting a Jar File Using a URL
e139. Accessing a Password-Protected URL

See also: Datagram    Encodings    HTTP    Hostnames and IP Addresses    Multicast    Sockets   


© 2002 Addison-Wesley.