Java 从 url 获取 http 响应代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18395203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:11:30  来源:igfitidea点击:

get http response code from a url

javahttp

提问by anonymous

I want to write a Java program which will hit a URL and will print the status code(i.e., 200, 404, etc.). I am doing this using the HttpUrlConnectionapi, but it only shows the exception, and does not print the status code.

我想编写一个 Java 程序,它将访问一个 URL 并打印状态代码(即 200、404 等)。我正在使用HttpUrlConnectionapi执行此操作,但它仅显示异常,并且不打印状态代码。

URL url = new URL("https://abc.com/test.html");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();  
System.out.println("code: "+code);

采纳答案by Soosh

I tried the your code as the following and it worked fine for me:

我尝试了你的代码如下,它对我来说很好:

import java.net.*;

public class Action 
{

    public static void main(String[] args)
    {
        try
        {
            URL url = new URL("http://localhost:8888");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            int code = connection.getResponseCode();  
            System.out.println("code: "+code);
        }
        catch(Exception e)
        {

        }

    }
}


also with google.


也用谷歌。

回答by Juned Ahsan

You will get a response code from a URLonly if you are able to reach that URL. In your code you seems to be using a non existing URL and hence must be getting not reachable host exception.

URL仅当您能够访问该 URL 时,您才会从 a 获得响应代码。在您的代码中,您似乎使用了一个不存在的 URL,因此必须获得无法访问的主机异常。

Try to reach a valid URL and check the response code:

尝试访问有效的 URL 并检查响应代码:

URL url = new URL("https://google.com");

回答by Jhanvi

URL url = new URL("https://www.google.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();  
System.out.println("code: "+code);

Try using some other url, because the url you are using is invalid. 'https://abc.com/test.html' - no such page exists, so it is giving exception. try a valid url and it will work fine.

尝试使用其他网址,因为您使用的网址无效。' https://abc.com/test.html' - 不存在这样的页面,所以它给出了例外。尝试一个有效的网址,它会正常工作。

回答by Sandy

Even I am getting the same exception i.e java.net.ConnectException: Connection timed out: connect if I am not adding the proxy & port in your code.

即使我得到了同样的异常,即 java.net.ConnectException: Connection timed out: connect 如果我没有在你的代码中添加代理和端口。

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)

This exception you are getting because you are executing the code on your organization behind your organization proxy.

您之所以会遇到此异常,是因为您正在组织代理后面的组织上执行代码。

please use the below modified code. you will get the 200 OK as responseCode.

请使用以下修改后的代码。您将获得 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();
            }

        }

    }

NOTE: 1. You need to get the proxyHost IP from your organization network admin. 2. You should use HttpsURLConnection for accessing https URL.

注意: 1. 您需要从您的组织网络管理员那里获取 proxyHost IP。2. 你应该使用 HttpsURLConnection 来访问 https URL。