【问题标题】:How to get HTTP response code for a URL in Java?如何在 Java 中获取 URL 的 HTTP 响应代码?
【发布时间】:2011-09-22 00:13:53
【问题描述】:

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

【问题讨论】:

  • 我不会说重复,因为他想要响应代码,但@Ajit 你应该检查一下。添加一些实验,你就可以开始了。
  • 而不是要求别人为你做你的工作。请证明您至少尝试过自己完成这项任务。显示您当前的代码以及您如何尝试完成此任务。如果您希望有人不费吹灰之力地为您完成工作,您可以雇用某人并付钱给他们。
  • 他提出了什么要求?当他不知道该怎么做时,他寻求帮助,而不是旋转他的轮子。他正在按预期使用社区。​​span>

标签: java http http-status-codes


【解决方案1】:

HttpURLConnection:

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

int code = connection.getResponseCode();

这绝不是一个可靠的例子;你需要处理IOExceptions 之类的。但它应该让你开始。

如果您需要更强大的功能,请查看HttpClient

【讨论】:

  • 在我的具体情况下,使用您的方法,我得到一个 IOException(“无法通过代理进行身份验证”),这通常是一个 http 错误 407。有没有一种方法可以获得精度( http 错误代码)关于 getRespondeCode() 方法引发的异常?顺便说一句,我知道如何处理我的错误,我只想知道如何区分每个异常(或至少是这个特定的异常)。谢谢。
  • @grattmandu03 - 我不确定。看起来您遇到了stackoverflow.com/questions/18900143/…(不幸的是没有答案)。您可以尝试使用更高级别的框架,例如 HttpClient,它可能会让您更好地控制如何处理此类响应。
  • 好的,谢谢您的回答。我的工作是调整旧代码以使用此代理,并且更少的修改更多的客户将理解我的工作。但我想,这对我来说(现在)是做我想做的事的唯一方法。还是谢谢。
  • 你需要在 finally 块中调用 disconnect() 吗?
  • 这可能取决于,我会做一些研究。 docs如果持久连接当时处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。,这并不能保证。文档还说 表示在不久的将来不太可能向服务器发出其他请求。调用 disconnect() 不应暗示此 HttpURLConnection 实例可用于其他请求。 如果您使用 InputStream 读取数据,则应在 finally 块中使用 close() 该流.
【解决方案2】:
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();

【讨论】:

  • +1 以获得更简洁(但功能齐全)的示例。很好的示例 URL (background) :)
  • 在线程“main”java.net.ConnectException 中出现异常:连接被拒绝:连接我不知道为什么会这样。
  • 题外话,我想知道连接可以生成的所有响应代码 - 有文档吗?
  • 如何使用基本身份验证检查此网址
  • 加一个用于建议网址google.com/humans.txt
【解决方案3】:

您可以尝试以下方法:

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 中出现异常:连接被拒绝:连接。我不知道原因
【解决方案4】:
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);
    }
}

【讨论】:

    【解决方案5】:
    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?
    【解决方案6】:

    这对我有用:

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

    希望这可以帮助某人:)

    【讨论】:

      【解决方案7】:

      这对我有用:

                  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 中有重定向也可以工作
      【解决方案8】:

      您可以使用 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();
      }
      

      【讨论】:

        【解决方案9】:

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

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

        【讨论】:

        • 这根本不能回答问题。
        【解决方案10】:

        试试这段检查 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");
        }
        

        【讨论】:

          【解决方案11】:

          这是一个完整的静态方法,你可以适应设置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;
              }
            }
          

          【讨论】:

            【解决方案12】:

            这是一个老问题,但让我们以 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...
            }
            
            (...)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-06-05
              • 1970-01-01
              • 1970-01-01
              • 2013-05-23
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多