Java——URL类

版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/89073363

URL定义

统一资源标识符(Uniform Resource Identifier ,URL)是采用一种特定语法标识一个资源的字符串。所标识的资源可能是服务器上的一个文件。Java的URL网络类可以让你通过URL去练级网络服务器并获取资源。
URL的格式如下:

protocol://host:port/path?query#fragment
例如:https://www.baidu.com/

protocol(协议)可以是HTTP,HTTPS,FTP和File,port为端口号,path为文件路径及文件名。

URL类

构造函数

方法 描述
URL(String spec) 从 String表示形成一个 URL对象。
URL(String protocol, String host, int port, String file) 创建 URL从指定对象 protocol , host , port数,和 file 。
URL(String protocol, String host, int port, String file, URLStreamHandler handler) 创建 URL从指定对象 protocol , host , port数, file和 handler 。
URL(String protocol, String host, String file) 从指定的 protocol名称, host名称和 file名称创建一个URL。
URL(URL context, String spec) 通过在指定的上下文中解析给定的规范来创建一个URL。
URL(URL context, String spec, URLStreamHandler handler) 通过在指定上下文中使用指定的处理程序解析给定规范来创建URL。

方法

方法 描述
boolean equals(Object obj) 将此URL与其他对象进行比较。
String getAuthority() 获取此的授权部分 URL 。
Object getContent() 获取此URL的内容。
Object getContent(类[] classes) 获取此URL的内容。
int getDefaultPort() 获取与此 URL的协议的默认端口号。
String getFile() 获取此 URL的文件名。
String getHost() 获取此 URL的主机名(如适用)。
String getPath() 获取此 URL的路径部分。
int getPort() 获取此 URL的端口号。
String getProtocol() 获取此 URL的协议名称。
String getQuery() 获取此 URL的查询部分。
String getRef() 获取此的锚定(也称为“参考”) URL 。
String getUserInfo() 获取该 URL的userInfo部分。
int hashCode() 创建适合哈希表索引的整数。
URLConnection openConnection() 返回一个URLConnection实例,表示与URL引用的远程对象的URL 。
URLConnection openConnection(Proxy proxy) 与openConnection()相同,但连接将通过指定的代理进行; 不支持代理的协议处理程序将忽略代理参数并进行正常连接。
InputStream openStream() 打开与此 URL ,并返回一个 InputStream ,以便从该连接读取。
boolean sameFile(URL other) 比较两个URL,不包括片段组件。
static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) 设置应用程序的 URLStreamHandlerFactory 。
String toExternalForm() 构造这个 URL的字符串 URL 。
String toString() 构造此 URL的字符串表示 URL 。
URI toURI() 返回相当于此URL的URI 。

URL类本身不会根据RFC2396中定义的转义机制对任何URL组件进行编码或解码。 来电者有责任编码任何需要在调用URL之前进行转义的字段,并对从URL返回的任何转义字段进行解码。 此外,由于URL不具有URL转义的知识,因此不能识别同一URL的编码或解码形式之间的等同性。 例如,两个URL:

  http://foo.com/hello world/ 
  http://foo.com/hello%20world 

将被视为不相等。
注意:在某些情况下, URI类确实执行其组件字段的转义。 管理URL编码和解码的推荐方法是使用URI ,并使用toURI()和URI.toURL()在这两个类之间进行转换。
也可以使用URLEncoder和URLDecoder类,但仅适用于与RFC2396中定义的编码方案不同的HTML表单编码。
URL类的常规使用

package dream.URL.test;

import java.io.*;
import java.net.*;

public class URLTest {

	//获取网页数据
	static void getFromURL1(String url){
		URL u;
		try {
			u = new URL(url);
			URLConnection uc=u.openConnection();
			InputStream in=uc.getInputStream();
			byte[] b=new byte[1024];
			int len;
			while((len=in.read(b))!=-1)
			{
			    System.out.println(new String(b,0,len));
			}
			in.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
		return ;
	}
	//获取URL网页数据
	static void getFromURL2(String url){
		URL u=null;
	    BufferedReader in=null;
		try {
			u = new URL(url);
			in=new BufferedReader(new InputStreamReader(u.openStream(),"UTF-8"));
	        String str;
	        while((str=in.readLine())!=null) {
	     	   System.out.println(str);
	        }
	        in.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			if(in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return ;
	}
	
	static void getContent(String url) {
	    try {
			URL u=new URL(url);
			System.out.println(u.getPort());
			Object ob=u.getContent();
			System.out.println("i get a "+ob.getClass().toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
		return;
	}
	//获取URL服务器数据
	static void getURLDetails(String url){
		
		try {
		   URL u=new URL(url);
		   System.out.println(u);
		   System.out.println"文件类型:"+);
	       System.out.println("使用的协议: " + u.getProtocol()); //获取URL里面的超文本协议    
	       //System.out.println("The user info is " + u.getUserInfo());//
	        
	       String host = u.getHost();
	        if (host != null) {
	          int atSign = host.indexOf('@');  
	          if (atSign != -1) host = host.substring(atSign+1);
	          System.out.println("主机名称:" + host);   
	        } else {          
	          System.out.println("主机名称: null.");   
	        }

	        System.out.println("端口号: " + u.getDefaultPort());
	        System.out.println("默认端口:" + u.getDefaultPort());	        
	        System.out.println("路径: " + u.getPath());
	        System.out.println("定位位置: " + u.getRef());
	        System.out.println("请求参数: " + u.getQuery());
	        System.out.println("文件名及请求参数:" + u.getFile());
	        System.out.println("验证信息:" + u.getAuthority());
	      } catch (MalformedURLException ex) {
	        System.err.println(url + " is not a URL I understand.");
		}
		return ;
	}
	
	 //从输入流中获取字节数组
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] b = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建字节流缓冲区存取字节
        while((len = inputStream.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    //获取文件的类型和名字
    public static String getFileName(String url) {
    	int sta1=url.lastIndexOf(".");
    	char[] tchar=new char[1024];
    	url.getChars(sta1, url.length(), tchar, 0);
 
    	int sta2=url.lastIndexOf("/");
    	char[] tchar1=new char[1024];
    	url.getChars(sta2+1, sta1, tchar1, 0);
    	String s=new String();
    	for(char i:tchar1) {
    		if(i=='\0') {
    			break;
    		}
    		s+=i;
    	}
    	for(char i:tchar) {
    		if(i=='\0') {
    			break;
    		}
    		s+=i;
    	}
    	return s;
    }
	//从URL下载文件
	public static void downLoadFormURL(String url,String filePath) {
		try {
			URL u=new URL(url);//获取URL
			HttpURLConnection conn=(HttpURLConnection) u.openConnection();
			conn.setConnectTimeout(3000);//设置连接超时时间
			//屏蔽403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			InputStream in=conn.getInputStream();//获取输入流
			byte[] data=readInputStream(in);
			File file=new File(filePath);
			if(!file.isDirectory()) {
				System.out.println("存放路径不对");
			}
			if(!file.exists()) {//路径不存在就创建
				file.mkdirs();
			}
			System.out.println(getFileName(url));
			File save=new File(file.getPath()+"//"+getFileName(url));
			System.out.println(save.getPath());
			FileOutputStream fos = new FileOutputStream(save);
		    fos.write(data);
		    if(fos!=null){
		          fos.close();
		      }
		    if(in!=null){
		          in.close();
		    }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.err.println(e.toString());
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
		//System.out.println(getFileName("http://www.baidu.com"));
		String url="https://ss1.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=10da86d6df43ad4bb92e40c0b2035a89/"
				+ "03087bf40ad162d93b3a196f1fdfa9ec8b13cde9.jpg";
		downLoadFormURL(url,"E:\\");//下载文件
		//getFromURL2("http://www.baidu.com");
		//getContent("http://d1.sina.com.cn/200903/11/168512_whh_950_450.jpg");
		//getURLDetails("http://www.runoob.com/index.html?language=cn#j2se");
	}

}

URLConnections类

抽象类URLConnection是表示应用程序和URL之间的通信链接的所有类的超类。 该类的实例可以用于从URL引用的资源中读取和写入。

  • 通过在URL上调用openConnection方法创建连接对象。
  • 设置参数和一般请求属性被操纵。
  • 使用connect方法实现与远程对象的实际连接。
  • 远程对象变得可用。 可以访问头字段和远程对象的内容。
构造方法 描述
protected URLConnection(URL url) 构造与指定URL的URL连接。

URLConnections类的方法

方法 说明
void addRequestProperty(String key, String value) 添加由键值对指定的一般请求属性。
abstract void connect() 打开与此URL引用的资源的通信链接,如果此类连接尚未建立。
boolean getAllowUserInteraction() 返回此对象的 allowUserInteraction字段的值。
int getConnectTimeout() 返回连接超时的设置。
Object getContent() 检索此URL连接的内容。
Object getContent(类[] classes) 检索此URL连接的内容。
String getContentEncoding() 返回 content-encoding标题字段的值。
int getContentLength() 返回 content-length标题字段的值。
long getContentLengthLong() 返回 content-length标头字段的值为long。
String getContentType() 返回 content-type标题字段的值。
long getDate() 返回 date标题字段的值。
static boolean getDefaultAllowUserInteraction() 返回 allowUserInteraction字段的默认值。
static String getDefaultRequestProperty(String key) (已弃用 )在获得适当的URLConnection实例之后,应该使用实例特定的getRequestProperty方法。
boolean getDefaultUseCaches() 返回默认值为 URLConnection的 useCaches标志。
boolean getDoInput() 返回此 URLConnection的 doInput标志的值。
boolean getDoOutput() 返回此 URLConnection的 doOutput标志的值。
long getExpiration() 返回 expires标题字段的值。
static FileNameMap getFileNameMap() 从数据文件加载文件名映射(模拟)。
String getHeaderField(int n) 返回的值 n th头字段。
String getHeaderField(String name) 返回命名头字段的值。
long getHeaderFieldDate(String name, long Default) 返回以日期解析的命名字段的值。
int getHeaderFieldInt(String name, int Default) 返回被解析为命名字段的值。
String getHeaderFieldKey(int n) 返回的关键 n th头字段。
long getHeaderFieldLong(String name, long Default) 返回被解析为命名字段的值。
Map<String,List> getHeaderFields() 返回不可修改的标题字段的映射。
long getIfModifiedSince() 返回此对象的 ifModifiedSince字段的值。
InputStream getInputStream() 返回从此打开的连接读取的输入流。
long getLastModified() 返回 last-modified标题字段的值。
OutputStream getOutputStream() 返回写入此连接的输出流。
Permission getPermission() 返回一个权限对象,该对象表示创建此对象所表示的连接所需的权限。
int getReadTimeout() 返回读取超时的设置。
Map<String,List> getRequestProperties() 返回此连接的一般请求属性的不可修改映射。
String getRequestProperty(String key) 返回此连接的命名的常规请求属性的值。
URL getURL() 返回此 URLConnection的 URL字段的值。
boolean getUseCaches() 返回此 URLConnection的 useCaches字段的值。
static String guessContentTypeFromName(String fname) 根据URL的指定“文件”组件,尝试确定对象的内容类型。
static String guessContentTypeFromStream(InputStream is) 根据输入流开头的字符,尝试确定输入流的类型。
void setAllowUserInteraction(boolean allowuserinteraction) 设置这个 URLConnection的 allowUserInteraction字段的值。
void setConnectTimeout(int timeout) 设置打开与此URLConnection引用的资源的通信链接时使用的指定超时值(以毫秒为单位)。
static void setContentHandlerFactory(ContentHandlerFactory fac) 设置应用 ContentHandlerFactory的ContentHandlerFactory。
static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) 将所有将来的 URLConnection对象的 allowUserInteraction字段的默认值设置为指定的值。
static void setDefaultRequestProperty(String key, String value) 已弃用 在获得适当的URLConnection实例之后,应该使用实例特定的setRequestProperty方法。 调用此方法将不起作用。
void setDefaultUseCaches(boolean defaultusecaches) 将 useCaches字段的默认值设置为指定值。
void setDoInput(boolean doinput) 设置的值 doInput领域本 URLConnection指定值。
void setDoOutput(boolean dooutput) 设置的值 doOutput领域本 URLConnection指定值。
static void setFileNameMap(FileNameMap map) 设置FileNameMap。
void setIfModifiedSince(long ifmodifiedsince) 设置的值 ifModifiedSince这个领域 URLConnection到指定值。
void setReadTimeout(int timeout) 将读取超时设置为指定的超时时间,以毫秒为单位。
void setRequestProperty(String key, String value) 设置一般请求属性。
void setUseCaches(boolean usecaches) 设置的值 useCaches这个领域 URLConnection到指定值。
String toString() 返回 String此URL连接的表示。

猜你喜欢

转载自blog.csdn.net/Dog_dream/article/details/89073363