这是我将尝试的一般想法,但您如何处理 AsyncTask 取决于您在获得状态后正在做什么。我会做这样的事情:
private class GetHttpStatus extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String[] params) {
private boolean status;
//this will be the string you pass in execute()
String urlString = params[0];
HttpURLConnection httpConnection;
try {
URL gurl = new URL(urlString);
URLConnection connection = gurl.openConnection();
connection.setConnectTimeout(5 * 1000);
httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
status = true;
}
} catch (Exception e) {
status = false;
} finally {
if(httpConnection != null) httpConnection.disconnect();
}
return status;
}
@Override
protected Void onPostExecute(Boolean result) {
//Here you'll do whatever you need to do once the connection
//status has been established
MyActivity.notifyHttpStatus(result);
}
}
//in your Activity somewhere, you would call...
new GetHttpStatus.execute("http://www.amazon.com");