我对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.1rn");
bw.write("Accept: text/htmlrn");
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.36rn");
bw.write("rn");
} 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,为了从服务器获得响应,我必须执行任何过程吗?
首先,您需要调用 flush()
以确保在准备好时缓冲的数据实际写入套接字。
bw.write("GET / HTTP/1.1rn");
bw.write("Accept: text/htmlrn");
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.36rn");
bw.write("rn");
bw.flush(); // ADD THIS LINE
其次,您需要发送有效的 HTTP 1.1 标头。RFC 非常复杂,这是依赖备受推崇的现有 HTTP 客户端库的另一个原因,但这里和其他地方的信息应该会有所帮助,例如这个。例如,您至少缺少一个 Host: 标头。