您的位置:首页 > 理论基础 > 计算机网络

android 网络编程(一、URL)

2015-10-26 17:45 465 查看
URL类

URL (UniformResource Locator)对象代表统一资源定位器,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更复杂的对象的引用,例如对数据库或搜索引擎的查询。通常情况而言,URL可以由协议名、主机、端口和资源组成。即满足如下格式:

protocol://host:port/resourceName

如下例子:使用URL(String protocol, String host, int port, String file)方式创建

public
static void main(String[] args) {

try {

URL
myUrl =new URL("http","192.168.0.244", 9987,"/hbtcInspect/interface/shopInspectionInfo/");

InputStreamReader inputS =new
InputStreamReader(myUrl.openStream());

BufferedReader in =new
BufferedReader(inputS);

;

String inputLine;

while ((inputLine = in.readLine()) !=null) {

System.out.println(inputLine);

}

System.out.println(myUrl);

in.close();

}
catch (Exception e) {

e.printStackTrace();

}

}

注:我们通常网络请求使用的是URLConnection,但是这里我们却没有发现URLConnection,大家来看myUrl.openStream()的源码:

/**

* Equivalent to {@code openConnection().getInputStream(types)}.

*/

public final InputStream openStream()throws IOException {

return openConnection().getInputStream();

}

/**

* Returns a new connection to the resource referred to by this URL.

*

* @throws IOException if an error occurs while opening the connection.

*/

public URLConnection openConnection()
throws IOException {

return streamHandler.openConnection(this);

}

实际上他使用的就是URLConnection.getInputStream()方法,只是自己封装了罢了。

在java.net包中定义了URL类,以下为URL类的使用方法

1.创建URL类

URL类的构造方法主要有如下几种

URL(String spec):使用指定的字符串构建。

URL(String protocol, String host, int port, String file):使用指定的协议、主机名、端口号、文件名创建。

URL(String protocol, String host, String file):使用指定的协议、主机名、文件名创建。

URL(URL context, String spec):使用基地址和相对URL创建

2.URL 的使用:

使用URL类的常用方法主要有如下几种。

String getAuthority():获得此URL的授权部分。

Object getContent():获得此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部分。

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

InputStream openStream():打开到此URL的连接,并返回一个用于从该连接读入的InputStream。

boolean sameFile(URL other):比较两个URL,不包括片段部分。

protected void set(String protocol, String host, int port, String file, String ref):设置URL的字段。

static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac):设置应用程序的URLStreamHandlerFactory。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: