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でSteeamを獲得したほうがいいです。
 
5.コンテンツをURLに書き込む
例えば、URLに文字列を書き、サーバーが得たら、逆文字列を返します。通常は以下の手順で実行されます。
   1.Create a URL.   2.Retrieve the URLConnect object.   3.Set output capability on the URLConnection.url Connection.set Douutput(true);   4.Open a connection to the resource.   5.Get an out put stream from the connection.   6.Write to the out put stream.    7.Close the out put 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();
  
 
アクセス方式はジャバTestURLConnection Writer http://localhost:8080/urltest/reverse abcです。
サーバー側はServletで処理します。具体的には添付のコードをご参照ください。