Introduction:
Sometimes you want to know if a service is responding correctly before you give it the actual task.
With a small piece of code you can test if the response you get is an apropriate one.
The imports are from the :
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
The example:
boolean isUp = false;
HttpClient client = new HttpClient();
//********************************************************
//Optional for https sessions. You can run it through a trusted proxy
// to get the certificates.
//client.getHostConfiguration().setProxy("MyProxy", MyProxyPort);
//********************************************************
GetMethod method = new GetMethod("http://www.google.nl/");
try{
client.executeMethod(method);
if(method.getStatusCode()==200){
isUp = true;
}
}catch(Exception e) {
System.err.println(e);
}finally {
method.releaseConnection();
}
return isUp;
Conclusion:
It is quiet easy to check before you send your query or data to a url to check if it will respond correctly.
So have fun!
Geen opmerkingen:
Een reactie posten