Internet


Basic Authentication

Authenticator.setDefault(new Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
      System.out.printf( "url=%s, host=%s, ip=%s, port=%s%n",
            getRequestingURL(), getRequestingHost(),
            getRequestingSite(), getRequestingPort() );
      return new PasswordAuthentication("user", "pass".toCharArray());
   }
});  

URL url = new URL("http://www.domain.de/user/" );

System.out.println(
      new Scanner(url.openStream() ).
      useDelimiter( "\\Z" ).next() );


Proxy-Authentifizierung

Möglichkeit 1:

System.setProperty( "http.proxyUserName", proxyUser );
System.setProperty( "http.proxyPassword", proxyPass );

Möglichkeit 2:

URLConnection conn = url.openConnection();

String base64 = "Basic " +
      new sun.misc.BASE64Encoder().encode((user + ":" +
      passwd).getBytes() );

conn.setRequestProperty("Proxy-Authorization", "Basic " +
      new sun.misc.BASE64Encoder().encode((proxyUser + ":" +
      proxyPass).getBytes()) );

conn.connect();

InputStream in = conn.getInputStream();

Content einer URL lesen

StringBuffer sb = null;
try {
   URL url = new URL("https://localhost:80/index.htm");
   BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
   String row;
   while((row = in.readLine()) != null) {
      // readLine() entfernt das/die newline-zeichen
      sb.append(row);
   }
   in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}        
System.out.println(sb.toString());