说说httpurlconnection的实例化过程吧,在爬虫中webcollector 使用的就是直接封装了httpurconenction 实例化过程为
URL url=null;
HttpURLConnection httpURLConnection=null;
try {
url=new URL(“http://www.baidu.com“);
httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.addRequestProperty(“User-Agent”, “Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0”);
}catch (IOException e){
e.printStackTrace();
}
这只是我们看到的表面内部实现是使用了复杂的封装的,这里的HttpURLConnection 是java.net里的抽象类,具体实现是在url.openConnection()中交给了URL累的处理器handler获取
public URLConnection openConnection() throws IOException {
return this.handler.openConnection(this);
}
handler是URL类所拥有的处理器handler = getURLStreamHandler(this.protocol)
在函数getURLStreamHandler中对于没有指定handler的URL类
if(handler == null) {
String packagePrefixList = null;
packagePrefixList = (String)AccessController.doPrivileged(new GetPropertyAction(“java.protocol.handler.pkgs”, “”));
if(packagePrefixList != “”) {
packagePrefixList = packagePrefixList + “|”;
}
packagePrefixList = packagePrefixList + "sun.net.www.protocol";
handler2 = new StringTokenizer(packagePrefixList, "|");
label86:
while(true) {
String packagePrefix;
do {
if(handler != null || !handler2.hasMoreTokens()) {
break label86;
}
packagePrefix = handler2.nextToken().trim();
} while(protocol.equalsIgnoreCase("gopher") && packagePrefix.equals("sun.net.www.protocol") && !enableGopher);
try {
String clsName = packagePrefix + "." + protocol + ".Handler";
Class cls = null;
//根据协议选择包,使用反射将handler类的具体实现加载进来
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException var12) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if(cl != null) {
cls = cl.loadClass(clsName);
}
}
if(cls != null) {
handler = (URLStreamHandler)cls.newInstance();
}
} catch (Exception var13) {
;
}
}
}
上面例子中就会根据协议选择
package sun.net.www.protocol.http;
import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import sun.net.www.protocol.http.HttpURLConnection;
public class Handler extends URLStreamHandler {
protected String proxy;
protected int proxyPort;
protected int getDefaultPort() {
return 80;
}
public Handler() {
this.proxy = null;
this.proxyPort = -1;
}
public Handler(String proxy, int port) {
this.proxy = proxy;
this.proxyPort = port;
}
protected URLConnection openConnection(URL u) throws IOException {
return this.openConnection(u, (Proxy)null);
}
protected URLConnection openConnection(URL u, Proxy p) throws IOException {
return new HttpURLConnection(u, p, this);
}
}
加载,这里最终实例化一个类HttpURLConnection是
sun.net.www.protocol.http.HttpURLConnection的具体实例,这个类很大2000多行,这个sun包中的HttpURLConnection是继承了java.net包中的HttpURLConnection的所以能够用父类做声明