gpt4 book ai didi

android - 如何从 Android Activity 中 ping 网站并获得响应?

转载 作者:太空宇宙 更新时间:2023-11-03 11:45:03 30 4
gpt4 key购买 nike

我用了isReachable,没用,用了ConnectivityManager和getNetworkInfo;实际上,这仅用于检查我是否已连接到 Internet...

但问题是我想检查是否可以上网,所以我想ping一个网站看看是否有响应。

最佳答案

获取方法:

private void executeReq(URL urlObject) throws IOException{
HttpURLConnection conn = null;

conn = (HttpURLConnection) urlObject.openConnection();
conn.setReadTimeout(100000); //Milliseconds
conn.setConnectTimeout(150000); //Milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);

// Start connect
conn.connect();
String response = convertStreamToString(conn.getInputStream());
Log.d("Response:", response);
}

你可以调用它

try {
String parameters = ""; //
URL url = new URL("http://alefon.com" + parameters);
executeReq(url);
}
catch(Exception e){
//Error
}

要检查 Internet 连接,请使用:

private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (null == ni)
Toast.makeText(this, "no internet connection", Toast.LENGTH_LONG).show();
else {
Toast.makeText(this, "Internet Connect is detected .. check access to sire", Toast.LENGTH_LONG).show();
//Use the code above...
}
}

关于android - 如何从 Android Activity 中 ping 网站并获得响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9873489/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com