How do I check the status code of the server http response in java?

Asked

Viewed 1,969 times

4

Good morning, you guys.

I would like to know how to do in java to check whether the response received from the server was successful or not.

Can someone help me with that?

  • What code do you have so far? could you please post ?

  • I haven’t even started yet, I just wanted to know which method is using some HTTP type API in java. It’s like, I’ll send a request to the server, and I just wanted to know the answer, if it’s 200, 404, 500 or other.

2 answers

3


Your question is very wide, because the answer may or may not suit you according to what you want to do, which you should explain better.

However, I will try to help you in the same way. For example:

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

public class Download {
    public static void main(String[] args) throws IOException {
        HttpURLConnection c1 = (HttpURLConnection) new URL("http://grepcode.com").openConnection();
        int code1 = c1.getResponseCode();
        System.out.println(code1);

        HttpURLConnection c2 = (HttpURLConnection) new URL("http://grepcode.com/naoexiste").openConnection();
        int code2 = c2.getResponseCode();
        System.out.println(code2);
    }
}

This code establishes two connections and displays the HTTP status code. The first will show 200 (ok) and the second will show 404 (page not found). Use 2xx status for success and 4xx or 5xx for errors, where 4xx errors are probably your errors and 5xx errors are probably server problems.

If the connection cannot be established, a IOException will be released. In your, code it is important that you test for them and know how to treat them properly.

It is possible to make changes and customizations in the object HttpURLConnection before to call the getResponse(). Such changes would be to define headers, change the HTTP method (for example, use POST instead of GET), define that you would like to upload, configure caches, proxies, timeouts, etc. See the javadocs to see what methods you could use in this case.

0

I solved my problem using Webresponse as follows:

WebClient client = new WebClient(BrowserVersion.getDefault());
HtmlPage paginaResponse = (HtmlPage) client.getPage("http://www.website.com");

WebResponse response = paginaResponse.getWebResponse();

      if (response.getStatusCode() == 200) {


         //codigo

      }

I decided to do it this way, because I was already using Webclient and Htmlpage in the method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.