使用Java检查网页是否存在

时间:2017-07-11 19:58:18

标签: java web connection httpurlconnection

我正在使用Java检查我传入的网址的响应。这是我正在使用的当前代码。但是,我一直收到连接拒绝错误。我正在使用基本的Google主页进行测试,以便我知道我的代码的粗略草稿是有效的。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;


public class connectTest {


public static void main(String[] args)
{

    boolean test = pageExists();

}
public static boolean pageExists(){

        int returnCode= 0;

       try {
             HttpURLConnection.setFollowRedirects(false);
             String httpsURL = "https://www.google.com/";
             URL testUrl = new URL(httpsURL);
             HttpsURLConnection con = 
             (HttpsURLConnection)testUrl.openConnection();

             returnCode= con.getResponseCode();
             System.out.println(returnCode);


       } catch (Exception e) {
              e.printStackTrace();
       }

       if (returnCode== HttpURLConnection.HTTP_OK){
           return true;
       }
       else if (returnCode== HttpURLConnection.HTTP_BAD_REQUEST || returnCode== 
        HttpURLConnection.HTTP_NOT_FOUND ){
           return false;
       }
       else 
       {
           System.out.println("The return code was not 200,400 or 404");
           return false;

       }


    }  
  }

这是我运行以下内容时遇到的错误:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.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.plainConnect0(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.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)

0 个答案:

没有答案