dadi520 发表于 2013-2-7 20:35:16

URL 的具体分析

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);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处理,具体见附件代码
页: [1]
查看完整版本: URL 的具体分析