2011-06-24 176 views
108

请告诉我获取特定网址URL响应代码的步骤或代码。如何获取Java中的URL的HTTP响应代码?

+0

看到这个:HTTP://www.codingdiary.com/developers/developers/diary/javaapi/java/net/ SampleCode/HttpURLConnectionGetResponseCodeExampleCode.html –

+2

我不会说重复,因为他想要响应代码,但@Ajit你应该检查出来。添加一点实验,你很好去。 – slezica

+2

而不是要求其他人为你做你的工作。请证明你至少试图完成你自己的任务。显示您当前的代码以及您如何尝试完成此任务。如果你想要一个人为你做你的工作,而你没有努力,你可以聘请一个人并付款。 –

回答

142

HttpURLConnection

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

int code = connection.getResponseCode(); 

这决不是一个坚固的例子;你需要处理IOException和什么。但它应该让你开始。

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

+1

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

+2

@ grattmandu03 - 我不确定。看起来像你遇到http://stackoverflow.com/questions/18900143/getting-http-407-error-as-an-ioexception(很遗憾没有答案)。你可以尝试使用像HttpClient这样的更高级别的框架,这可能会让你更好地控制你如何处理这样的响应。 –

+0

好的,谢谢你的回答。我的工作是调整一个旧代码来处理这个代理,并且更少的修改让客户理解我的工作。但我想,这对我来说(现在)是我想做的唯一方法。不管怎么说,还是要谢谢你。 – grattmandu03

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

+1更简洁(但功能齐全)的示例。不错的例子URL([背景](http://humanstxt.org/)):) – Jonik

+0

在线程中获取异常“main”java.net.ConnectException:拒绝连接:连接 我不知道为什么我得到这个。 –

+0

刚刚脱离主题,我想知道连接可以生成的所有响应代码 - 是否有文档? – Skynet

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

在线程“main”中获取异常java.net.ConnectException:连接被拒绝:连接。我不知道分享 –

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

我们如何处理基本身份验证的网址? –

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

希望这可以帮助别人:)

1

这为我工作:

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

          } 


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

试试这个代码和平被检查的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"); 
}