Reputation: 1910
I have one GET Restful service
that return JSON. I have to get Response time of that service.
My requirement is that when i try to get JSON data from that service and if that service take more than 10 seconds then i have to redirect it some another page.
So how can i do this?
My code is given below
import java.net.URL;
import java.net.HttpURLConnection;
URL url = new URL(sURL);
HttpURLConnection req = (HttpURLConnection) url.openConnection();
req.connect();
if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ResponseCode = HTTP_OK");
}
I am using Java with Eclipse Mars 1.
Upvotes: 2
Views: 2774
Reputation: 9197
First set timeout and then catch the timeout exception and make a new request:
try {
req.setConnectTimeout(TimeUnit.SECONDS.toMillis(10));
req.setReadTimeout(TimeUnit.SECONDS.toMillis(10));
[...] readData(req);
} catch (SocketTimeoutException e) {
// do request again
}
Edit: readTimeout is optional. I'm using it always bacause I want wait too long for data.
Upvotes: 0
Reputation: 13
firstly you want to setReadTimeout or setConnectTimeout in url request and catch java.net.SocketTimeoutException then in catch redirect to your new url as the code below
import java.net.URL;
import java.net.HttpURLConnection;
try {
URL url = new URL(sURL);
HttpURLConnection req = (HttpURLConnection) url.openConnection();
req .setReadTimeout(10000); // 10 seconds
if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ResponseCode = HTTP_OK");
}
} catch (java.net.SocketTimeoutException e) {
req = (HttpURLConnection) new URL("your new URL").openConnection();
}
Upvotes: 0
Reputation: 4274
long start = System.currentTimeMillis();
chain.doFilter(request, response);
long elapsedTime = System.currentTimeMillis() - start;
if(elapsedTime <= 10){
System.out.println("ResponseCode = HTTP_OK");
}
check elapsedTime less then or equal to 10 or not, here request and respone is from ServletRequest and ServletResponse
Upvotes: 0
Reputation: 2968
HttpURLConnection
has a setConnectTimeout
method.
You can use it and catch the SocketTimeoutException
, then you can redirect to the other page you want.
Edit
If you want the response anyway, and the duration also, you can take the current system time juste before the call, then after response compare the time that your request took.
Upvotes: 3