iam*_*rem 5 java sockets https http
我正在尝试使用 java制作一个简单的HTTP/HTTPS 客户端。到目前为止,我在 Client.java 文件中所做的工作就在这里。
当我尝试访问 www.google.com:80 时,一切正常。我在响应 BufferedReader 中获得了完整的 HTML 内容。
但是,当我尝试访问 www.google.com:443 时,没有数据通过 BufferedReader
对于 www.facebook.com:80,
HTTP/1.1 302 Found
Run Code Online (Sandbox Code Playgroud)
另外,当我尝试使用 www.facebook.com:443 时,出现以下错误:
Exception in thread "main" java.net.SocketException: Connection reset
Run Code Online (Sandbox Code Playgroud)
我哪里出错了?为什么我无法获得 HTTPS 站点的任何响应?
public class Client {
public static void main(String[] args) throws IOException {
//String host = args[0];
//int port = Integer.parseInt(args[1]);
//String path = args[2];
int port = 80;
String host = "www.google.com";
String path = "/";
//Opening Connection
Socket clientSocket = new Socket(host, port);
System.out.println("======================================");
System.out.println("Connected");
System.out.println("======================================");
//Declare a writer to this url
PrintWriter request = new PrintWriter(clientSocket.getOutputStream(),true);
//Declare a listener to this url
BufferedReader response = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Sending request to the server
//Building HTTP request header
request.print("GET "+path+" HTTP/1.1\r\n"); //"+path+"
request.print("Host: "+host+"\r\n");
request.print("Connection: close\r\n");
request.print("\r\n");
request.flush();
System.out.println("Request Sent!");
System.out.println("======================================");
//Receiving response from server
String responseLine;
while ((responseLine = response.readLine()) != null) {
System.out.println(responseLine);
}
System.out.println("======================================");
System.out.println("Response Recieved!!");
System.out.println("======================================");
request.close();
response.close();
clientSocket.close();
}
}
Run Code Online (Sandbox Code Playgroud)
HTTPS 已加密;它是通过 SSL 的 HTTP。您不能只发送原始 HTTP 请求。如果您在没有先建立安全连接的情况下开始发送数据,服务器将立即断开您的连接(因此出现连接重置错误)。您必须首先建立 SSL 连接。在这种情况下,您需要使用SSLSocket(via SSLSocketFactory,另请参阅example ) 而不是 a 。Socket
这就像针对 HTTPS 情况更改一行代码一样简单(如果算上异常规范并且端口号更改为 443,则为三行):
Socket clientSocket = SSLSocketFactory.getDefault().createSocket(host, port);
Run Code Online (Sandbox Code Playgroud)
请注意,在本例中clientSocket,将是SSLSocket(派生自Socket)的一个实例。
但是,如果您将此作为较大应用程序的一部分(而不只是学习体验),请考虑现有的库,例如 Apache 的HttpClient(也支持 HTTPS)或内置库HttpURLConnection,并且HttpsURLConnection如果您需要更基本的东西。如果您需要在应用程序中嵌入服务器,您可以使用内置的HttpServer或HttpsServer.
还有 EJP 在他的评论中提到的问题。