Java/Network Protocol/HttpsURLConnection

Материал из Java эксперт
Перейти к: навигация, поиск

Accessing a Password-Protected URL

 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
public class Main {
  public static void main(String[] argv) throws Exception {
    Authenticator.setDefault(new MyAuthenticator());
    URL url = new URL("http://hostname:80/index.html");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
      System.out.println(str);
    }
    in.close();
  }
}
class MyAuthenticator extends Authenticator {
  
  protected PasswordAuthentication getPasswordAuthentication() {
    String promptString = getRequestingPrompt();
    System.out.println(promptString);
    String hostname = getRequestingHost();
    System.out.println(hostname);
    InetAddress ipaddr = getRequestingSite();
    System.out.println(ipaddr);
    int port = getRequestingPort();
    String username = "name";
    String password = "password";
    return new PasswordAuthentication(username, password.toCharArray());
  }
}





Certification for HTTPS

  
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.cert.CertPath;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 9999);
    socket.startHandshake();
    SSLSession session = socket.getSession();
    java.security.cert.Certificate[] servercerts = session.getPeerCertificates();
    List mylist = new ArrayList();
    for (int i = 0; i < servercerts.length; i++) {
      mylist.add(servercerts[i]);
    }
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath cp = cf.generateCertPath(mylist);
    FileOutputStream f = new FileOutputStream("CertPath.dat");
    ObjectOutputStream b = new ObjectOutputStream(f);
    b.writeObject(cp);
  }
}





Disabling Certificate Validation in an HTTPS Connection

 
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      public void checkClientTrusted(X509Certificate[] certs, String authType) {
      }
      public void checkServerTrusted(X509Certificate[] certs, String authType) {
      }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    URL url = new URL("https://hostname/index.html");
  }
}





Dump a page using the HTTPS protocol

 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
  public static void main(String[] argv) throws Exception {
    URL url = new URL("https://www.server.ru");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
      System.out.println(inputLine);
    in.close();
  }
}





Read data from a URL

  
 
//Corrected version by Quentin Nerden (kenden at gmail dot com) 
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebReader {
  static void getData(String address) throws Exception {
    URL page = new URL(address);
    StringBuffer text = new StringBuffer();
    HttpURLConnection conn = (HttpURLConnection) page.openConnection();
    conn.connect();
    InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
    
    BufferedReader buff = new BufferedReader(in);
    String line = buff.readLine();
    while (line != null) {
        text.append(line + "\n");
        line = buff.readLine();
    }
    System.out.println(text.toString());
  }
  public static void main(String[] arguments) throws Exception {
    getData("http://jexp.ru");
  }
}