Good morning, guys.
I would like to know how to do this in java to see if the response received from the server was successful or not.
Can anyone help me with this?
Good morning, guys.
I would like to know how to do this in java to see if the response received from the server was successful or not.
Can anyone help me with this?
Your question is very broad, because the answer may or may not suit you according to what you want to do, which you should explain better.
However, I'll try to help you anyway. 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 shows the HTTP status code. The first one will show 200 (ok) and the second one will show 404 (page not found). Use the 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 can not be established, a IOException
will be thrown. In your code, it is important that you test for them and know how to treat them properly.
You can make changes and customizations to the object HttpURLConnection
before calling getResponse()
. Such changes would be to set headers , change the HTTP method (for example, use POST instead of GET), set what you would like to upload, set up caches, proxies timeouts , etc. See javadocs to see what methods you could use in this case.
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 this, as I was already using the WebClient and the HtmlPage method.