URL类的使用

 模拟服务器,用IE浏览器代替客户端

代码如下:

package com.hbsi.net;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerDemo {

/**

 * @param args

 */

public static void main(String[] args) throws Exception{

ServerSocket ss=new ServerSocket(9009);

Socket s=ss.accept();

String ip=s.getInetAddress().getHostAddress();

System.out.println(ip+"ok,成功连接");

PrintWriter pwout=new PrintWriter(s.getOutputStream(),true);

pwout.println("<font color='red' size=7>恭喜访问成功。。。。。</font>");

s.close();

ss.close();

}

}

URl类的使用

URlUniform Resource Locator)类代表统一资源定位器,统一资源定位器是指互联网“资源”的名称。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据可或搜索引擎的查询。通常URL可以由协议名、主机、端口和资源组成。URL的格式为"protocol://host:port/resourceName"。例如,URL地址“http://www.163.index.htm”。

URL提供了多个构造方法用于创建URL对象,常用的有两个:

public URL(String str)

Public URL(URL context,String str)

可以通过绝对地址创建对象:

URL url=new URL(“www.baidu.com”);

如果获得URL对象之后,就可以调用如下方法来访问该URL对应的资源。

String getFile():获取此URL的资源名。

String getHost():获取此URL的主机名。

String getPath():获取此URL的路径部分。

String getPort():获取此URL的端口号。

String getProtocol():获取此URL的协议名称。

Sting getQuery():获取此URL的查询字符串部分。

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

InputStream openStream():打开此URL的链接,并返回一个用于读取该URL资源的InputStream

例:

package com.hbsi.net;

import java.net.*;

import java.io.*;

public class TestNet {

/**

 * @param args

 */

public static void main(String[] args) throws Exception{

URL url=new URL("http://www.sina.com/");

InputStream in=url.openStream();

BufferedReader brin=new BufferedReader(new InputStreamReader(in));

String line=null;

FileOutputStream fos=new FileOutputStream("F:\\mylovewebsite.html");

while((line=brin.readLine())!=null){

fos.write(line.getBytes());

System.out.println(line);

}

brin.close();

fos.close();

}

}

这样就可以在F盘中保存了新浪网首页

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值