java--URL

URL类

URL(Uniform Resource Locator)是一致资源定位器的简称,它表示Internet上某一资源的地址。通过URL我们可以访问Internet上的各种网络资源,比如最常见的WWW,FTP站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。
String getFile() 获取此 URL 的文件名。 
String getHost() 获取此 URL 的主机名(如果适用)。 
String getPath() 获取此 URL 的路径部分。 
int getPort() 获取此 URL 的端口号。 //当端口号没有设置的时候,返回-1,在系统中,改为默认端口为80
String getProtocol() 获取此 URL 的协议名称。 

String getQuery() 获取此 URL 的查询部 

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

InputStream openStream() :打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream .打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。此方法是下面方法的缩写: openConnection().getInputStream()

import java.net.*;
class URLDemo 
{
	public static void main(String[] args) throws MalformedURLException
	{
		URL url = new URL("http://192.168.1.254:8080/myweb/demo.html?name=haha&age=30");
		System.out.println("getProtocol() :"+url.getProtocol());
		System.out.println("getHost() :"+url.getHost());
		System.out.println("getPort() :"+url.getPort());
		System.out.println("getPath() :"+url.getPath());
		System.out.println("getFile() :"+url.getFile());
		System.out.println("getQuery() :"+url.getQuery());
	}
}
结果:

getProtocol() :http
getHost() :192.168.1.254
getPort() :8080
getPath() :/myweb/demo.html
getFile() :/myweb/demo.html?name=haha&age=30
getQuery() :name=haha&age=30


抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。

private void showDir()throws Exception
{
	ta.setText("");
	String urlPath = tf.getText();//http://192.168.1.254:8080/myweb/demo.html
	URL url = new URL(urlPath);
	URLConnection conn = url.openConnection();   
	InputStream in = conn.getInputStream();
	byte[] buf = new byte[1024];
	int len = in.read(buf);
	ta.setText(new String(buf,0,len));
}
private void showDir()throws Exception
	{
		ta.setText("");
		String url = tf.getText();//http://192.168.1.254:8080/myweb/demo.html
		int index1 = url.indexOf("//")+2;
		int index2 = url.indexOf("/",index1);

		String str = url.substring(index1,index2);
		String[] arr = str.split(":");
		String host = arr[0];
		int port = Integer.parseInt(arr[1]);
		String path = url.substring(index2);
		//ta.setText(str+"...."+path);
		Socket s = new Socket(host,port);	
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		out.println("GET "+path+" HTTP/1.1");
		out.println("Accept: */*");
		out.println("Accept-Language: zh-cn");
		out.println("Host: 192.168.1.254:11000");
		out.println("Connection: closed");
		out.println();
		out.println();
		BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String line = null;
		while((line=bufr.readLine())!=null)
		{
			ta.append(line+"\r\n");
		}
		s.close();
	}
两者功能相同。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值