0

我的问题是如何向服务器请求 HTTPS 请求,并获取响应内容?不使用任何第三方 API?

笔记!!这是 HTTPS,不是 HTTP!

例如,我给一个 URL: " www.google.com" 和 port 443,它可以从服务器获取 index.html。

如何实现这样的客户端?有人可以给出一些示例代码吗?

我已经写了这个,但它不起作用。

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class HttpsClient {
public static void main(String[] args) {
  PrintStream out = System.out;

  // Getting the default SSL socket factory
  SSLSocketFactory f = 
     (SSLSocketFactory) SSLSocketFactory.getDefault();
  out.println("The default SSL socket factory class: "
     +f.getClass());
  try {
  // Getting the default SSL socket factory
     SSLSocket c =
       (SSLSocket) f.createSocket("www.google.com", 443);
     printSocketInfo(c);
     c.startHandshake();
     BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
        c.getOutputStream()));
     BufferedReader r = new BufferedReader(new InputStreamReader(
        c.getInputStream()));
     w.write("GET / HTTP/1.0");
     w.newLine();
     w.newLine(); // end of HTTP request
     w.flush();
     String m = null;
     while ((m=r.readLine())!= null) {
        out.println(m);
     }
     w.close();
     r.close();
     c.close();
  } catch (IOException e) {
     System.err.println(e.toString());
  }

}

4

0 回答 0