(Java) 自定义 low-level HTTPS get/post 请求

(Java) Custom made low-level HTTPS get/post request

我想提出自己的 GET/POST 请求。我可以在它是 HTTP 时执行此操作,但 HTTPS 对我不起作用。我不想使用 HttpURLConnection.

我试过的东西:

Socket s = SSLSocketFactory.getDefault().createSocket(new InetSocketAddress("https://www.google.com/", 443).getAddress(), 443);
s.setSoTimeout(60*1000);

String request = "GET https://www.google.com/ HTTP/1.1\r\n";
String[] headersArray = headers.split("\n");
for (int i = 0; i < headersArray.length; i++) {
    request += headersArray[i] +"\r\n";
}
request += "\r\n";

OutputStream os = s.getOutputStream();
os.write(request.getBytes("UTF8"));
os.flush();
//etc (reading response)

然而,在将请求写入输出流时,我得到:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.OutputStream.write(Unknown Source)

我做错了什么?

请注意,我希望能够做到这一点 "on the lowest level as possible" 这样我就可以拥有尽可能多的控制权并确切地知道发生了什么 sent/received。我尝试使用 HttpURLConnection(从 URL object 获得)来执行此操作,但它拒绝发送我给它的某些特殊 headers。

更新:问题已解决。

刚好需要更换

new InetSocketAddress("https://www.google.com/", 443)

new InetSocketAddress("www.google.com", 443)

虽然有点奇怪的错误,但我更希望在创建套接字期间从这里得到一个错误。

试试,

SSLSocket s = (SSLSocket) SSLSocketFactory.getDefault().createSocket("www.google.com", 443);
s.startHandshake();
s.setSoTimeout(60 * 1000);

OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();

String request = "GET https://www.google.com/ HTTP/1.1\r\n";
os.write(request.getBytes("UTF8"));
os.flush();

String str;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((str = reader.readLine()) != null) {
    System.out.println(str);
}