列表6是URLDemo3的源代码,它演示了把窗体数据发送给某个"了解"application/x-www-form-urlencoded内容类型的资源。它实现了前面提到的各种事务。
列表6: URLDemo3.java
// URLDemo3.java
import java.io.*;
import java.net.*;
class URLDemo3
{
ublic static void main (String [] args) throws IOException
{
// 检查最后两个参数和参数的数量
if (args.length < 2 || args.length % 2 != 0)
{
System.err.println ("usage: java URLDemo3 name value " +
"[name value ...]");
return;
}
// 建立程序连接服务器程序资源的URL对象,它返回一个窗体的名称/值对
URL url;
url = new URL
("http://banshee.cs.uow.edu.au:2000/~nabg/echo.cgi");
// 向某个特定协议对象返回表现http资源连接的引用
URLConnection uc = url.openConnection ();
// 验证连接的类型,必须是HttpURLConnection的
if (!(uc instanceof HttpURLConnection))
{
System.err.println ("Wrong connection type");
return;
}
// 表明程序必须把名称/值对输出到服务器程序资源
uc.setDoOutput (true);
// 表明只能返回有用的信息
uc.setUseCaches (false);
//设置Content-Type头部指示指定URL已编码数据的窗体MIME类型
uc.setRequestProperty ("Content-Type",
"application/x-www-form-urlencoded");
// 建立名称/值对内容发送给服务器
String content = buildContent (args);
//设置Content-Type头部指示指定URL已编码数据的窗体MIME类型