java.net.URLクラスを使用してアクセスがHTTPコード401で失敗する場合(Authenticator)

WEBサーバーからHTMLを取得し書き出すプログラムでこんなん出ましたが

java.io.IOException: Server returned HTTP response code: 401...

java.net.Authenticatorクラスを使って解決してみます。

http://forum.java.sun.com/thread.jspa?threadID=449825&messageID=2041397を参考にして

こんな感じでアクセスできました。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class HtmlPrinter {

  public static void main(String[] args) {
    try {
      
      // 認証設定
      Authenticator.setDefault(new Authenticator() {

        String username = "username";
        String password = "password";

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(this.username,
              (this.password.toCharArray()));
        }
      });      

      // 普通は以下だけでOK
      URL url = new URL("http://www.  ...co.jp/");      
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      String line;
      while ((line = in.readLine()) != null) {
        System.out.println(line);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

職場の環境によっては、必要になったりしますね。