163

Please tell me the steps or code to get the response code of a particular URL.

Andrew Swan
  • 13,427
  • 22
  • 69
  • 98
Ajit
  • 1,639
  • 2
  • 11
  • 3
  • See this :http://www.codingdiary.com/developers/developers/diary/javaapi/java/net/SampleCode/HttpURLConnectionGetResponseCodeExampleCode.html – Harry Joy Jun 24 '11 at 12:35
  • 2
    I wouldn't say duplicate, since he wants the response code, but @Ajit you should check that out anyway. Add a little experimentation and you're good to go. – salezica Jun 24 '11 at 12:36
  • 2
    Rather than making demands for other people to do your work for you. Please demonstrate that you have at least attempted to accomplish this task on your own. Show your current code and how you have attempted to accomplish this task. If you want some one to do your work for you with no effort on your part you can hire someone and pay them. – Patrick W. McMahon Feb 02 '15 at 17:07
  • 1
    What demand did he make? He asked for help, instead of spinning his wheels when he had no idea what to do. He was using the community as it was intended. – Danny Remington - OMS Aug 06 '18 at 18:03

12 Answers12

204

HttpURLConnection:

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

int code = connection.getResponseCode();

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.

Ravi
  • 30,829
  • 42
  • 119
  • 173
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
  • 2
    In my specific case and with your method, I get an IOException ("Failed to authenticate with proxy") which is usually an http error 407. Is there a way where I can get a precision (the http error code) about the exception raised by the getRespondeCode() method? By the way, I know how to handle my error, and I just want to know how to differentiate each exception (or at least this specific exception). Thanks. – grattmandu03 Sep 19 '13 at 15:23
  • 2
    @grattmandu03 - I'm not sure. Looks like you're running into http://stackoverflow.com/questions/18900143/getting-http-407-error-as-an-ioexception (which unfortunately doesn't have an answer). You could try using a higher-level framework like HttpClient, which would probably give you a bit more control over how you handle responses like that. – Rob Hruska Sep 19 '13 at 17:00
  • Ok thank you for your answer. My job is to adapt an old code to work with this proxy, and less modifications more the client will understand my work. But I guess, it's for me (right now) the only way to do what I want. Thanks anyway. – grattmandu03 Sep 19 '13 at 18:12
  • Do you need to call disconnect() in a finally block? – Andrew Swan Nov 21 '14 at 00:35
  • It probably depends, I would do some research. The [docs](https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html) say *Calling the `disconnect()` method may close the underlying socket if a persistent connection is otherwise idle at that time.*, which doesn't guarantee. Docs also say *Indicates that other requests to the server are unlikely in the near future. Calling `disconnect()` should not imply that this `HttpURLConnection` instance can be reused for other requests.* If you're using an `InputStream` to read data, you should `close()` that stream in a `finally` block. – Rob Hruska Nov 21 '14 at 05:04
  • doesn'nt work if there is a redirection. It's safer to use subhasish-sahu 's method! – Daniel May 16 '18 at 13:41
43
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
kwo
  • 1,834
  • 1
  • 15
  • 9
14

You could try the following:

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");
        }
    }
}
senderle
  • 145,869
  • 36
  • 209
  • 233
8
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);
    }
}
Raja Singh
  • 91
  • 1
  • 3
4

This has worked for me :

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

                          }


                   }
Subhasish Sahu
  • 1,297
  • 8
  • 9
3

This is what worked for me:

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

Hope this helps someone :)

Jeverick
  • 51
  • 7
3

Efficient way to get data(With uneven payload) by 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();
    }
}
user8024555
  • 149
  • 1
  • 5
2

Try this piece of code which is checking the 400 error messages

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");
}
vorburger
  • 3,439
  • 32
  • 38
2

This is the full static method, which you can adapt to set waiting time and error code when IOException happens:

  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;
    }
  }
Mladen Adamovic
  • 3,071
  • 2
  • 29
  • 44
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());
neoeahit
  • 1,689
  • 2
  • 21
  • 35
0

you can use java http/https url connection to get the response code from the website and other information as well here is a sample 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();
}
captainchhala
  • 831
  • 1
  • 7
  • 14
0

Its a old question, but lets to show in the REST way (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...
}

(...)