如何在Java中获取URL的HTTP响应代码?

Aji*_*jit 135 java http http-status-codes

请告诉我获取特定URL的响应代码的步骤或代码.

Rob*_*ska 170

HttpURLConnection:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
Run Code Online (Sandbox Code Playgroud)

这绝不是一个有力的例子; 你需要处理IOExceptions等等.但它应该让你开始.

如果您需要具有更多功能的东西,请查看HttpClient.

  • 在我的特定情况下,使用您的方法,我得到一个IOException("无法通过代理进行身份验证"),这通常是一个http错误407.有没有办法可以获得有关引发的异常的精度(http错误代码)通过getRespondeCode()方法?顺便说一句,我知道如何处理我的错误,我只想知道如何区分每个异常(或至少这个特定的异常).谢谢. (2认同)
  • @ grattmandu03 - 我不确定.看起来你遇到了http://stackoverflow.com/questions/18900143/getting-http-407-error-as-an-ioexception(遗憾的是没有答案).您可以尝试使用像HttpClient这样的更高级别的框架,这可能会让您更好地控制如何处理这样的响应. (2认同)

小智 37

URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
Run Code Online (Sandbox Code Playgroud)

  • +1更简洁(但功能齐全)的例子.很好的示例网址([背景](http://humanstxt.org/)):) (11认同)

小智 10

您可以尝试以下方法:

class ResponseCodeCheck 
{

    public static void main (String args[]) throws Exception
    {

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

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://www.google.com");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        int statusCode = http.getResponseCode();
        System.out.println(statusCode);
    }
}
Run Code Online (Sandbox Code Playgroud)