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


144

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



2
我不会说重复,因为他想要响应代码,但是@Ajit无论如何都应该检查一下。添加一些实验,您就可以开始了。
slezica 2011年

2
而不是要求他人为您完成工作。请证明您至少尝试自己完成此任务。显示您当前的代码以及您如何尝试完成此任务。如果您希望有人为您做事,而您却不费吹灰之力,则可以雇用某人并付钱。
Patrick W. McMahon

他有什么要求?他寻求帮助,而不是在不知道该怎么做的时候转动轮子。他按预期使用社区。
Danny Remington-OMS

Answers:


180

HttpURLConnection

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

int code = connection.getResponseCode();

这绝不是一个有力的例子。您将需要处理IOExceptions和诸如此类的东西。但这应该可以帮助您入门。

如果您需要更多功能,请查看HttpClient


2
在我的特定情况下,并使用您的方法,我得到一个IOException(“无法通过代理进行身份验证”),通常是一个HTTP错误407。有没有一种方法可以使我对引发的异常有一个精确的了解(http错误代码)通过getRespondeCode()方法?顺便说一句,我知道如何处理我的错误,我只想知道如何区分每个异常(或至少是这个特定的异常)。谢谢。
grattmandu03 2013年

2
@ grattmandu03-我不确定。看起来您正在遇到stackoverflow.com/questions/18900143/…(不幸的是,它没有答案)。您可以尝试使用更高级别的框架(例如HttpClient),这可能使您对如何处理此类响应有更多控制。
Rob Hruska 2013年

好的,谢谢您的回答。我的工作是改编旧代码以与此代理一起使用,而较少的修改会使客户更了解我的工作。但是我想,这对我来说(现在)是我想要做的唯一方法。不管怎么说,还是要谢谢你。
grattmandu03 2013年

您是否需要在finally块中调用disconnect()?
Andrew Swan

这可能取决于我会做一些研究。该文档调用disconnect()方法可能关闭基础套接字如果持续连接在当时是闲置的。,但不能保证。文档还说,这表明在不久的将来不太可能向服务器发出其他请求。调用disconnect()不应暗示可以将该HttpURLConnection实例重用于其他请求。如果您使用InputStream读取数据,则应close()在一个finally块中传输该数据流。
Rob Hruska

38
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();

11
+1代表更简洁(但功能齐全)的示例。很好的示例URL(背景):)
Jonik

在线程“主”中获取异常java.net.ConnectException:连接被拒绝:connect我不知道为什么得到这个。
加内萨·维贾亚库玛

刚好脱离话题,我试图了解连接可以生成的所有响应代码-是否有文档?
天网2015年

如何使用基本身份验证检查网址
Satheesh Kumar

加上一个提示的网址google.com/humans.txt
PC。

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");
        }
    }
}

在线程“主”中获取异常java.net.ConnectException:连接被拒绝:connect。我不知道那个人-Ganesa
Vijayakumar

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);
    }
}

4

这对我有用:

            import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpGet;  
            import org.apache.http.impl.client.DefaultHttpClient;
            import org.apache.http.HttpResponse;
            import java.io.BufferedReader;
            import java.io.InputStreamReader;



            public static void main(String[] args) throws Exception {   
                        HttpClient client = new DefaultHttpClient();
                        //args[0] ="http://hostname:port/xyz/zbc";
                        HttpGet request1 = new HttpGet(args[0]);
                        HttpResponse response1 = client.execute(request1);
                        int code = response1.getStatusLine().getStatusCode();

                         try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
                            // Read in all of the post results into a String.
                            String output = "";
                            Boolean keepGoing = true;
                            while (keepGoing) {
                                String currentLine = br.readLine();          
                                if (currentLine == null) {
                                    keepGoing = false;
                                } else {
                                    output += currentLine;
                                }
                            }
                            System.out.println("Response-->"+output);   
                         }

                         catch(Exception e){
                              System.out.println("Exception"+e);  

                          }


                   }

完善。即使URL中存在重定向也有效
Daniel

2

这对我有用:

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

public class UrlHelpers {

    public static int getHTTPResponseStatusCode(String u) throws IOException {

        URL url = new URL(u);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        return http.getResponseCode();
    }
}

希望这可以帮助某人:)


2

尝试这段代码,检查400条错误消息

huc = (HttpURLConnection)(new URL(url).openConnection());

huc.setRequestMethod("HEAD");

huc.connect();

respCode = huc.getResponseCode();

if(respCode >= 400) {
    System.out.println(url+" is a broken link");
} else {
    System.out.println(url+" is a valid link");
}

1

扫描仪获取有效数据的有效方式(有效负载不均匀)。

public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");  // Put entire content to next token string, Converts utf8 to 16, Handles buffering for different width packets

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

这根本无法回答问题。
pringi '18

1

这是完整的静态方法,当IOException发生时,您可以使用它来设置等待时间和错误代码:

  public static int getResponseCode(String address) {
    return getResponseCode(address, 404);
  }

  public static int getResponseCode(String address, int defaultValue) {
    try {
      //Logger.getLogger(WebOperations.class.getName()).info("Fetching response code at " + address);
      URL url = new URL(address);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(1000 * 5); //wait 5 seconds the most
      connection.setReadTimeout(1000 * 5);
      connection.setRequestProperty("User-Agent", "Your Robot Name");
      int responseCode = connection.getResponseCode();
      connection.disconnect();
      return responseCode;
    } catch (IOException ex) {
      Logger.getLogger(WebOperations.class.getName()).log(Level.INFO, "Exception at {0} {1}", new Object[]{address, ex.toString()});
      return defaultValue;
    }
  }

0
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

。。。。。。。

System.out.println("Value" + connection.getResponseCode());
             System.out.println(connection.getResponseMessage());
             System.out.println("content"+connection.getContent());

如何处理具有基本身份验证的URL?
Satheesh Kumar

0

您可以使用java http / https url连接从网站获取响应代码以及其他信息,这也是示例代码。

 try {

            url = new URL("https://www.google.com"); // create url object for the given string  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(https_url.startsWith("https")){
                 connection = (HttpsURLConnection) url.openConnection();
            }

            ((HttpURLConnection) connection).setRequestMethod("HEAD");
            connection.setConnectTimeout(50000); //set the timeout
            connection.connect(); //connect
            String responseMessage = connection.getResponseMessage(); //here you get the response message
             responseCode = connection.getResponseCode(); //this is http response code
            System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
            connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}

0

这是一个古老的问题,但让我们以REST方式(JAX-RS)进行展示:

import java.util.Arrays;
import javax.ws.rs.*

(...)

Response response = client
    .target( url )
    .request()
    .get();

// Looking if response is "200", "201" or "202", for example:
if( Arrays.asList( Status.OK, Status.CREATED, Status.ACCEPTED ).contains( response.getStatusInfo() ) ) {
    // lets something...
}

(...)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.