我对 HTTPS 请求有疑问,我想制作一个非常简单的 Java 程序来读取 GET 请求的响应。问题是我看不到任何响应,并且程序在屏幕上什么也不打印。
这是代码:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
public class Test
{
public static void main(String args[])
{
SSLSocket sock;
String host = "www.example.com";
try{
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sock = (SSLSocket) factory.createSocket(host, 443);
}
catch(IOException e)
{
e.printStackTrace();
return;
}
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
bw.write("GET / HTTP/1.1\r\n");
bw.write("Accept: text/html\r\n");
bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
bw.write("\r\n");
} catch (IOException e) {
e.printStackTrace();
return;
}
try{
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer buffer = new StringBuffer();
String temp;
while((temp = br.readLine()) != null)
{
buffer.append(temp);
}
br.close();
System.out.println(buffer);
}
catch(IOException e)
{
e.printStackTrace();
return;
}
}
}
我正在将 SSLSocket 与 SSLSocketFactory 一起使用,是否需要执行任何程序才能从服务器获取响应?