Java URL クラス

URL(Uniform Resource Locator)は統一資源位置指定子の略で、インターネット上でリソースを特定するために使用されます。Java では、java.net.URLURL クラスは URL を処理する機能を提供し、開発者が URL オブジェクトの作成、URL の構成要素の解析、ネットワーク接続の確立を行うことを可能にします。


URL クラスの基本構造

標準的な URL は通常、次の部分で構成されます:

protocol://host:port/path?query#fragment

例:

https://www.example.com:8080/products?id=123#details

主要な構成要素

  1. プロトコル(Protocol):https
  2. ホスト(Host):www.example.com
  3. ポート(Port):8080
  4. パス(Path):/products
  5. クエリパラメータ(Query):id=123
  6. フラグメント(Fragment):details

URL オブジェクトの作成

Java は URL オブジェクトを作成するための複数のコンストラクタメソッドを提供しています:

1. 完全な URL 文字列を使用

例

try {
    URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
    e.printStackTrace();
}

2. プロトコル、ホスト、ファイルをそれぞれ指定

例

try {
    URL url = new URL("https", "www.example.com", "/index.html");
} catch (MalformedURLException e) {
    e.printStackTrace();
}

3. プロトコル、ホスト、ポート、ファイルを指定

例

try {
    URL url = new URL("https", "www.example.com", 8080, "/api/data");
} catch (MalformedURLException e) {
    e.printStackTrace();
}

URL クラスのよく使うメソッド

URL の各部分の情報を取得

例

URL url = new URL("https://www.example.com:8080/products?id=123#details");

System.out.println("プロトコル: " + url.getProtocol());  // https
System.out.println("ホスト: " + url.getHost());      // www.example.com
System.out.println("ポート: " + url.getPort());      // 8080
System.out.println("パス: " + url.getPath());      // /products
System.out.println("クエリ: " + url.getQuery());     // id=123
System.out.println("フラグメント: " + url.getRef());       // details

ネットワーク接続を開く

URL クラスにはネットワーク接続を開くためのいくつかのメソッドがあります:

  1. openConnection():URLConnection オブジェクトを返します
  2. openStream():入力ストリームを開き、データの読み取りに使用します

例

// openStream() を使用してウェブページの内容を読み取る
try (InputStream in = url.openStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

URL エンコードとデコード

URL では、特定の文字(スペース、中国語など)をエンコードする必要があります。Java はエンコードとデコードを処理するための URLEncoder クラスと URLDecoder クラスを提供しています。

URL エンコードの例

例

String query = "name=张三&age=25";
String encodedQuery = URLEncoder.encode(query, "UTF-8");
System.out.println(encodedQuery);  // 出力: name%3D%E5%BC%A0%E4%B8%89%26age%3D25

URL デコードの例

例

String decodedQuery = URLDecoder.decode(encodedQuery, "UTF-8");
System.out.println(decodedQuery);  // 出力: name=张三&age=25

実際の応用例

例1:ファイルのダウンロード

例

URL fileUrl = new URL("https://example.com/files/sample.pdf");
try (InputStream in = fileUrl.openStream();
     FileOutputStream out = new FileOutputStream("sample.pdf")) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
    }
    System.out.println("ファイルのダウンロードが完了しました");
} catch (IOException e) {
    e.printStackTrace();
}

例2:REST API の呼び出し

例

URL apiUrl = new URL("https://api.example.com/data?param1=value1");
try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(apiUrl.openStream()))) {
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    System.out.println("API レスポンス: " + response.toString());
} catch (IOException e) {
    e.printStackTrace();
}

注意事項

  1. 例外処理:URL コンストラクタは MalformedURLException をスローする可能性があり、ネットワーク操作は IOException をスローする可能性があります
  2. セキュリティ:信頼できないソースから URL を構築しないようにしてください
  3. パフォーマンス:頻繁なネットワークリクエストでは接続プールの使用を検討してください
  4. エンコード:特に非 ASCII 文字を含む場合は、URL エンコードを正しく処理してください
その他の関連