I am trying to implement ping using HttpGet but behavior is random.
I am having following code which test the internet/server connectivity:
boolean result = false;
HttpGet request = new HttpGet("www.MyServer.com");
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
HttpConnectionParams.setConnectionTimeout(httpParameters, 6000);
HttpConnectionParams.setSoTimeout(httpParameters, 6000);
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK)
{
result = true;
}
}
catch(Exception e)
{
e.printStackTrace();
result = false;
}
Log.d("App", "Ping Result:"+result);
Above code I am running in thread as it may take time. When I run this test for first time then I get result as true, but then after behavior is random, some times it given me error 'host unreachable' and I get result as false.
I just want to test is server is reachable from the currently configured Android network.
Is there any reliable API to test the internet/server connectivity?
UPDATE:
In a Service i have following function which initiates the test.
void startTest()
{
ServerTestThread mServerTestThread = new ServerTestThread()
mServerTestThread.start();
}
class ServerTestThread extends Thread
{
boolean result = false;
public void run()
{
//HttpGet code
//Send Message TO GUI Thread with result.
}
}
Above startTest
function is creating instance of the test thread and calling start function. when test is done I am sending message to main thread which contains the result.
Thanks.
There is no problem with your code. That means either:
So test setting timeout to some larger value, such as 60000(60sec), and check again. If it works, then you know it was because of timeout.
EDIT
Also please make this change, maybe it gives us more info:
Log.d("App", "Status:" + status);
if (status == HttpStatus.SC_OK)
{
result = true;
}
EDIT2
class ServerTestThread extends Thread
{
public static boolean result = false;
public static HttpGet request = new HttpGet("www.MyServer.com");
public static HttpParams httpParameters = new BasicHttpParams();
public static HttpClient httpClient = new DefaultHttpClient(httpParameters);
boolean result = false;
public void run()
{
//HttpGet code
//Send Message TO GUI Thread with result.
}
}
As a bonus, this will tell if you if you're connected to a network.