即使我得到相同的异常,即 java.net.ConnectException: Connection timed out: connect if 我没有在代码中添加代理和端口。
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at edu.sandip.TestURLConnection.main(TestURLConnection.java:23)
您收到此异常是因为您正在组织代理后面的组织上执行代码。
请使用以下修改后的代码。您将获得 200 OK 作为 responseCode。
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
public class TestURLConnection {
/**
* @param args
*/
public static void main(String[] args) {
try{
URL url = new URL("https://www.google.com/");
System.setProperty("https.proxyHost", "XXX.XXX.XXX.XX");
System.setProperty("https.proxyPort", "80");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("code: "+code);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意: 1. 您需要从您的组织网络管理员处获取 proxyHost IP。2. 你应该使用 HttpsURLConnection 来访问 https URL。