六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 124|回复: 0

URL 的具体分析

[复制链接]

升级  19.33%

21

主题

21

主题

21

主题

秀才

Rank: 2

积分
79
 楼主| 发表于 2013-2-7 20:35:16 | 显示全部楼层 |阅读模式
1. 创建 URL
 
URL(String spec)URL(String protocol, String host, String file)  
创建URL 相对路径时,有一个构造方法
URLs at the Gamelan site:
 http://www.gamelan.com/pages/Gamelan.game.html
 http://www.gamelan.com/pages/Gamelan.net.html
 
java URL object 对象构造
 
URL gamelan = new URL("http://www.gamelan.com/pages/");URL gamelanGames = new URL(gamelan, "Gamelan.game.html");URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html"); 

创建 URL 注意, 如果碰到特殊字符 如空格,可以依据一下方式转换. 

如果链接为:  http://foo.com/hello world/
则对应的java URL 对象为: URL url = new URL("http://foo.com/hello%20world");
注:如果不确定那些特殊字符需要编码, 可以使用 java.net.URI 类
 
URI uri = new URI("http", "foo.com", "/hello world/", "");URL url = uri.toURL(); 
 
2. 解析 URL
 
URL url = new URL("http://java.sun.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING"; System.out.println("authority: " + url.getAuthority()); System.out.println("host: " + url.getHost()); System.out.println("port: " + url.getPort()); System.out.println("query: " + url.getQuery()); System.out.println("path: " + url.getPath()); System.out.println("file: " + url.getFile()); System.out.println("content: " + url.getContent()); System.out.println("ref: " + url.getRef()); 
 
 
3. 读取 URL 里面的内容
URL url = null;url = new URL("http://www.163.com");  BufferedReader reader = new BufferedReader(    new InputStreamReader(url.openStream()));  String currentLine = null;while((currentLine = reader.readLine()) != null) {   System.out.println(currentLine);} 
4. 连接到 URL

当然,connect()方法不是必要的,如有些操作(getInputStream()等)会自动依赖于
connect() 方法,当然如果有必要,还是要显示调用

  try {  URL yahoo = new URL("http://www.yahoo.com/");  URLConnection yahooConnection = yahoo.openConnection();  yahooConnection.connect(); } catch (MalformedURLException e) {     // new URL() failed  . . . } catch (IOException e) {               // openConnection() failed  . . . } 

 
 
注: 一般不只直接要url 得到InputStream等,用URLConnection 获得Steam 比较好.
 
5. 写入内容到URL 中

例如: 写入一个字符串到URL, 然后服务器得到后,反向字符串后返回.
一般按以下步骤执行

   1. Create a URL.
   2. Retrieve the URLConnection object.
   3. Set output capability on the URLConnection. urlConnection.setDoOutput(true);
   4. Open a connection to the resource.
   5. Get an output stream from the connection.
   6. Write to the output stream.
    7. Close the output stream.

 
URL url = new URL(args[0]);URLConnection con = url.openConnection(); con.setDoOutput(true);OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());out.write("String =" + encodeStr);out.flush();out.close();  
 
访问方式为
java TestURLConnectionWriter http://localhost:8080/urltest/reverse abc
服务器端用Servlet处理,具体见附件代码
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表