(Java)自定义低级HTTPS获取/发布请求

时间:2015-09-01 18:55:15

标签: java ssl https request protocols

我想制作自己的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)

我在这里做错了什么?

请注意,我希望能够“尽可能在最低级别”执行此操作,以便尽可能多地控制并确切知道正在发送/接收的内容。我尝试使用HttpURLConnection(从URL对象获取),但它拒绝发送我给它的某些特殊标题。

更新:问题已解决。

只需要替换

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

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

虽然有点奇怪的错误,但我希望在套接字创建过程中出现错误。

1 个答案:

答案 0 :(得分:2)

尝试,

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);
}