[英]HTTP/HTTPS client, “connection reset” on HTTPS requests
我正在嘗試使用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
此外,當我嘗試使用www.facebook.com:443時,出現以下錯誤:
Exception in thread "main" java.net.SocketException: Connection reset
我哪里錯了? 為什么我無法獲得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();
}
}
HTTPS已加密; 它是通過SSL的HTTP。 您不能只發送原始HTTP請求。 如果您在沒有首先建立安全連接的情況下開始發送數據,則服務器將立即斷開連接(因此連接重置錯誤)。 您必須首先建立SSL連接。 在這種情況下,您需要使用SSLSocket
(通過SSLSocketFactory
,另請參見示例 )而不是Socket
。
它就像為HTTPS情況更改代碼的一行一樣簡單(如果計算異常規范並且端口號更改為443,則為三行):
Socket clientSocket = SSLSocketFactory.getDefault().createSocket(host, port);
請注意,在這種情況下, clientSocket
將是SSLSocket
的實例(從Socket
派生)。
但是,如果您將此作為更大應用程序的一部分(而不僅僅是學習經驗),請考慮現有的庫,例如Apache的HttpClient
(也支持HTTPS)或內置的HttpURLConnection
和HttpsURLConnection
如果需要)更基本的東西。 如果需要在應用程序中嵌入服務器,可以使用內置的HttpServer
或HttpsServer
。
也是EJP在評論中提到的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.