【JAVA网络流之URL】

一、URL

URL对象可以认为是URLConnection对象+Socket对象。

Java.lang.Object

         |-Java.net.URL

常用构造方法:

URL(String spec)
          根据 String 表示形式创建 URL 对象。

常用方法:

 URLConnection

openConnection()
          返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。

URLConnection

openConnection(Proxy proxy)
          
与 openConnection() 类似,所不同是连接通过指定的代理建立;不支持代理方式的协议处理程序将忽略该代理参数并建立正常的连接。

InputStream

openStream()
          
打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream

二、URLConnection

Java.lang.Object

         |-java.net.URLConnection

构造方法:

protected

URLConnection(URL url)
          构造一个到指定 URL 的 URL 连接。

常用方法:

 InputStream

getInputStream()
          返回从此打开的连接读取的输入流。

 OutputStream

getOutputStream()
          
返回写入到此连接的输出流。

 URL

getURL()
          
返回此 URLConnectionURL 字段的值。

 三、使用URL获取网页内容

使用的服务器:Apache

代码:

 1 package p08.URLDemo.p01.URLDemo;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.InputStreamReader;
 7 import java.net.URL;
 8 import java.net.URLConnection;
 9 
10 public class URLObjectDemo01 {
11     public static void main(String args[]) throws IOException
12     {
13         /**
14          * URL对象实际上是URLConnection对象+Socket对象
15          */
16         URL url=new URL("http"+ "://192.168.209.1:80//myWeb/index.html?name=zhangsan");
17         URLConnection urslc=url.openConnection();
18         InputStream is=urslc.getInputStream();
19         //两句可以合并成InputStream is=url.openStream();
20         InputStreamReader isr=new InputStreamReader(is);
21         BufferedReader br=new BufferedReader(isr);
22         String str=null;
23         while((str=br.readLine())!=null)
24         { 
25             System.out.println(str+System.getProperty("line.separator"));
26         }
27         br.close();
28     }
29 }
View Code

运行结果:

相对于使用Socket,这里省略了开始行与首部行,只有实体主体部分

原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/4238510.html