工厂设计模式
·URL类的setURLStreamHandlerFactory(URL StreamHandlerFactory fac)静态方法。
·URLStreamHandlerFactory类的createURLStreamHandler(String protocol)方法。
协议名与协议处理器的对应关系。
·工厂模式的工作原理
设计一个抽象的基类或者接口X,程序开发者可以根据实际的情况来编写不同的实现类Xy、Xz,
定义一个工程类,这个类中有一个getClass方法返回X类型的对象,getClass有参数a,根据不
同的参数返回不同的X的实现类对象。
URLConnection与HttpURLConnection类
·URLConnection与HttpURLConnection的作用。
URL类通过工程模式生成返回一个URLConnection类的对象,HttpURLConnection对象就是基于
http协议的这样的一个URLConnection类的子类。
·URLConnection的连接过程。
创建URLConnection对象的时候并没有马上就去连接远程资源。这样方便在与远程资源建立连接之前通过setRequestProperty方法设置相关属性
·setRequestProperty方法。--设置请求消息头
·getHeaderFields方法。--读取http服务器返回的响应消息头
·getInputStream和getOutputStream方法。
分别用于读取响应信息内容和写入请求信息。
·getHeaderField、getContentLength、getContentEncoding、getContentType等方法。
·一个HTTP连接可以被多个HttpURLConnection实例对象共享,调用HttpURLConnection的disconnect方法可以关闭底层共享网络。
编程实例:将访问www.google.com站点的HTTP请求消息的Accept-Language头分别设置成日文和中文后,
然后打印出www.google.com站点返回的所有响应消息头和网页内容。
import java.net.*;
import java.util.*;
import java.io.*;
public class GetGoogle {
/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args) throws Exception {
// TODO: Add your code here
System.out.println("获取日文页面:");
getContentByLanguage("ja");
System.out.println ("/n");
System.out.println("获取中文页面:");
getContentByLanguage("zh-CN");
}
public static void getContentByLanguage(String country) throws Exception{
URL urlGoogle = new URL("http://www.google.com");
HttpURLConnection googleConnection =(HttpURLConnection) urlGoogle.openConnection();
googleConnection.setRequestProperty("Accept-Language",country);
Map requests = googleConnection.getRequestProperties();
Set reqFields = requests.keySet();
Iterator itReq = reqFields.iterator();
// googleConnection.connect();
//开始获取请求消息头的信息内容
while(itReq.hasNext())
{
String field = (String)itReq.next();
System.out.println(field+" :"+googleConnection.getRequestProperty(field));
}
//开始获取响应的消息头信息
Map responses = googleConnection.getHeaderFields();
Set resFields = responses.keySet();
Iterator itRes = resFields.iterator();
while(itRes.hasNext())
{
String field = (String)itRes.next();
System.out.println(field+" :"+googleConnection.getHeaderField(field));
}
//开始获取响应的消息体信息
InputStream in = googleConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null)
{
System.out.println(strLine);
}
br.close();
googleConnection.disconnect();
}
}