我的问题是如何向服务器请求HTTPS请求,并获取响应内容?不使用任何第三方API?
请注意!这是HTTPS,而不是HTTP!
例如,我提供了一个网址:
“www.google.com
”和端口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());
}
}