现在的位置: 首页 > 综合 > 正文

从java网络编程学起(2)

2017年05月18日 ⁄ 综合 ⁄ 共 1157字 ⁄ 字号 评论关闭

URL  URLConnection
了解URL类的使用
了解URLConnection、
URL统一资源定位符可以使用此类找到互联网上的资源(一个简单的网页)

格式:

public Url(String protocol,String host,int port,String file)

实例:

package KownClass ;

import java.net.URL ;
import java.io.InputStream ;
import java.util.Scanner ;
public class FactoryDemo02{
	public static void main(String args[]) throws Exception {	// 所有异常抛出
<span style="white-space:pre">				</span>//协议,主机,端口,文件
		URL url = new URL("http","www.mldnjava.cn",80,"/curriculum.htm") ;
		InputStream input = url.openStream() ;	// 打开输入流
		Scanner scan = new Scanner(input) ;		// 实例化Scanner类
		scan.useDelimiter("\n") ;	// 设置读取分隔符
		while(scan.hasNext()){
			System.out.println(scan.next()) ;
		}
	}
};

2.URLconnecttion是封装访问远程网络资源一般方法的类 是通过他建立远程服务器的连接,
检查元辰资源的一些属性

getContentLengh() 取得内容长度
getContentType() 取得内容的类型
public InputStream getInputStream 取得输入流

实例2:

package KownClass ;

import java.net.URL ;
import java.net.URLConnection ;
import java.io.InputStream ;
import java.util.Scanner ;
public class FactoryDemo02{
	public static void main(String args[]) throws Exception {	// 所有异常抛出
		URL url = new URL("http://www.mldnjava.cn") ;
		URLConnection urlCon = url.openConnection() ;	// 建立连接
		System.out.println("内容大小:" + urlCon.getContentLength()) ;
		System.out.println("内容类型:" + urlCon.getContentType()) ;
	}
};

结果:内容大小:33220
内容类型:text/html

抱歉!评论已关闭.