从java网络编程学起(2)

来源:互联网 发布:hemingway软件 编辑:程序博客网 时间:2024/05/21 21:47
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

0 0
原创粉丝点击