|
For the HTTP protocol, writing to a URL means using CGI (the Common
Gateway Interface) scripts on the server.
Many CGI scripts use the POST METHOD for reading the data from the client
-- hence the term posting to a URL. Server-side scripts use the
POST METHOD to read from their standard input.
The following program uses a CGI script available at http://java.sun.com/cgi-bin/reverse . The script reverses any string supplied to it.
package networking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* Application to write to a URL, using a URLConnection class.
* (Note that this is NOT a Writer, like PrintWriter.)
*/
public class URLConnectionWriter
{
/**
* Main entry point
* @param args the command line arguments
* args[0] contains the URL to write to
*/
public static void main(String[] args)
{
if (args.length < 1)
{
System.err.println(
"Usage: java networking.Reverse <string-to-reverse>");
}
else
{
try
{
doWork(args[0]);
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
/**
* Do the actual work
* @param urlString the URL to connect to
*/
private static void doWork(String urlString)
throws MalformedURLException, IOException
{
// Translate into x-www-form-urlencoded format:
String reverseMe = URLEncoder.encode(urlString, "UTF-8");
// Open connection to URL
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection conn = url.openConnection();
// Set connection so it can do output
conn.setDoOutput(true);
// Provide input to server using the output stream.
PrintWriter out = new PrintWriter(conn.getOutputStream());
try
{
out.println("string=" + reverseMe);
}
finally
{
out.close();
}
// Read response from server
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String line = null;
try
{
while (true)
{
line = in.readLine();
if (line == null)
break;
System.out.println(line);
}
}
finally
{
in.close();
}
}
}
|
When supplied with the string:
"If it were done when 'twas done..."
this program uses the URLEncoder class to transform the
string into a form acceptable to the HTTP protocol:
If+it+were+done+when+%27twas+done...
The program gets the reversed output from the server and
prints it out:
...enod sawt' nehw enod erew ti fI
Note: This example was based on one in the Java Custom Networking
tutorial (http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html),
which made reference to the reverse script mentioned above. Unfortunately, the
script seems to have disappeared from Sun's Java web site.
|