Java中有一个URL类,可以获取指定url的内容。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://blog.csdn.net/someyuan");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String s = null;
StringBuffer sb = new StringBuffer();
while((s = br.readLine()) != null)
{
sb.append(s+"/r/n");
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
能够显示与浏览器中所得的页面源代码。
另一个例子,可以查看头文件中的信息
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://blog.csdn.net/someyuan");
URLConnection uc = url.openConnection();
Map m = uc.getHeaderFields();
Iterator it = m.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
一个URL对象生成后,其属性是不能被改变的,但是我们可以通过类URL所提供的方法来获取这些属性:
public String getProtocol() 获取该URL的协议名。
public String getHost() 获取该URL的主机名。
public int getPort() 获取该URL的端口号,如果没有设置端口,返回-1。
public String getFile() 获取该URL的文件名。
public String getRef() 获取该URL在文件中的相对位置。
public String getQuery() 获取该URL的查询信息。
public String getPath() 获取该URL的路径
public String getAuthority() 获取该URL的权限信息
public String getUserInfo() 获得使用者的信息
public String getRef() 获得该URL的锚
通过URL的方法openStream(),我们只能从网络上读取数据,如果我们同时还想输出数据,例如向服务器端的CGI程序发送一些数据,我们必须先 与URL建立连接,然后才能对其进行读写,这时就要用到类URLConnection了。CGI是公共网关接口(Common Gateway Interface)的简称,它是用户浏览器和服务器端的应用程序进行连接的接口,有关CGI程序设计,请读者参考有关书籍。
类 URLConnection也在包java.net中定义,它表示Java程序和URL在网络上的通信连接。当与一个URL建立连接时,首先要在一个 URL对象上通过方法openConnection()生成对应的URLConnection对象。例如下面的程序段首先生成一个指向地址http://blog.csdn.net/someyuan的对象,然后用openConnection()打开该URL对象上的一个连接,返回一个URLConnection对象。如果连接过程失败,将产生IOException.
Try{
URL netchinaren = new URL ("http://blog.csdn.net/someyuan");
URLConnectonn tc = netchinaren.openConnection();
}catch(MalformedURLException e){ //创建URL()对象失败
…
}catch (IOException e){ //openConnection()失败
…
}
类URLConnection提供了很多方法来设置或获取连接参数,程序设计时最常使用的是getInputStream()和getOurputStream(),其定义为:
InputSteram getInputSteram();
OutputSteram getOutputStream();
通过返回的输入/输出流我们可以与远程对象进行通信。看下面的例子:
URL url =new URL (http://blog.csdn.net/someyuan");
//创建一URL对象
URLConnectin con=url.openConnection();
//由URL对象获取URLConnection对象
DataInputStream dis=new DataInputStream (con.getInputSteam());
//由URLConnection获取输入流,并构造DataInputStream对象
PrintStream ps=new PrintSteam(con.getOutupSteam());
//由URLConnection获取输出流,并构造PrintStream对象
String line=dis.readLine(); //从服务器读入一行
ps.println("client…"); //向服务器写出字符串 "client…"
其中backwards为服务器端的CGI程序。实际上,类URL的方法openSteam()是通过URLConnection来实现的。它等价于
openConnection().getInputStream();
基于URL的网络编程在底层其实还是基于下面要讲的Socket接口的。WWW,FTP等标准化的网络服务都是基于TCP协议的,所以本质上讲URL编程也是基于TCP的一种应用.