检查服务器是否可用?

编程入门 行业动态 更新时间:2024-10-06 13:20:06
本文介绍了检查服务器是否可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我开发了一个连接到服务器的应用程序.因此,我想使用波纹管函数来检查服务器是否可用,但我不知道如何在 线程中使用它,以及每次需要检查服务器是否在活动中可用时如何调用它或片段:

I developing an application which connects to the server. Therefore i want use the bellow function to check if the server is available , But I don't know how I can use it in a thread and how call it each time when I need check if the server is available in activity or fragment :

static public boolean isURLReachable(Context context) { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try { URL url = new URL("192.168.1.13"); // Change to "google" for www test. HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(10 * 1000); // 10 s. urlc.connect(); if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine). Log.wtf("Connection", "Success !"); return true; } else { return false; } } catch (MalformedURLException e1) { return false; } catch (IOException e) { return false; } } return false; }

推荐答案

看看这段代码:

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { MyTask task = new MyTask(); task.execute(); } } private class MyTask extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(Void... params) { try { URL url = new URL("192.168.1.13"); // Change to "google" for www test. HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(10 * 1000); // 10 s. urlc.connect(); if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine). Log.wtf("Connection", "Success !"); return true; } else { return false; } } catch (MalformedURLException e1) { return false; } catch (IOException e) { return false; } } @Override protected void onPostExecute(Boolean result) { boolean bResponse = result; if (bResponse==true) { Toast.makeText(MainActivity.this, "server is available", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "server is not available", Toast.LENGTH_SHORT).show(); } } } }

更多推荐

检查服务器是否可用?

本文发布于:2023-11-23 21:51:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!