web-dev-qa-db-fra.com

Comment obtenir le code de réponse HTTP pour une URL en Java?

Dites-moi s'il vous plaît les étapes ou le code pour obtenir le code de réponse d'une URL particulière.

131
Ajit

HttpURLConnection :

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

int code = connection.getResponseCode();

Ce n'est en aucun cas un exemple robuste; vous aurez besoin de gérer IOExceptions et tout le reste. Mais cela devrait vous aider à démarrer.

Si vous avez besoin de quelque chose avec plus de possibilités, consultez HttpClient .

169
Rob Hruska
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
37
kwo

Vous pouvez essayer ce qui suit:

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");
        }
    }
}
10
Ashish Sharda
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
Raja Singh

Cela a fonctionné pour moi:

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

                          }


                   }
4
Subhasish Sahu

Essayez ce morceau de code qui vérifie les 400 messages d'erreur

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

C'est ce qui a fonctionné pour moi:

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

J'espère que ça aide quelqu'un :)

2
Jeverick
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
neoeahit

vous pouvez utiliser la connexion Java http/https url pour obtenir le code de réponse du site Web et d’autres informations. Voici un exemple de code.

 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
captainchhala

Moyen efficace d’obtenir des données (avec une charge utile inégale) par scanner.

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
user8024555