来自UrlConnection Java的响应

来自UrlConnection Java的响应,java,urlconnection,http-response-codes,Java,Urlconnection,Http Response Codes,到目前为止,我有这个片段 URLConnection connection = null; try { connection = (new URL("some_link")).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(

到目前为止,我有这个片段

URLConnection connection = null;
        try {
            connection = (new URL("some_link")).openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
        } catch (IOException e) {

        }

可能的响应代码是200和404,当响应代码是200(OK)时,它工作正常。我的问题是如何找到连接接收到的响应代码,例如:如果响应代码是404,则抛出异常并在那里执行smth。

将其设置为
HTTPUrlConnection
类型。然后可以使用
.getResponseCode()

使其成为一种
HTTPUrlConnection
类型。然后可以使用
.getResponseCode()

使用类似以下内容:

HttpURLConnection connection = (HttpURLConnection)new URL("URL_STRING")
                               .openConnection();


int statusCode = connection.getResponseCode();

使用类似以下内容:

HttpURLConnection connection = (HttpURLConnection)new URL("URL_STRING")
                               .openConnection();


int statusCode = connection.getResponseCode();

connection.setRequestMethod(“GET”)
是默认值。
connection.setRequestMethod(“GET”)
是默认值。