Java 检查到 URL 的 HTTP 连接(Android)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22443853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:45:30  来源:igfitidea点击:

Check HTTP connection to a URL (Android)

javaandroidhttpurlconnection

提问by Rory Price

I am trying to check a connection to a URL using HTTP in an app...

我正在尝试在应用程序中使用 HTTP 检查与 URL 的连接...

Process:

过程:

User clicks buttons, app sends a get request and then if successful it will return true, else false.

用户点击按钮,应用程序发送一个获取请求,如果成功则返回真,否则返回假。

 final Button mbutton = (Button) findViewById(R.id.httpcheck);
    mbutton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){

            public boolean isConnectedToServer(String url, int timeout) {
                try{
                    URL myUrl = new URL("http://www.google.co.uk");
                    URLConnection connection = myUrl.openConnection();
                    connection.setConnectTimeout(timeout);
                    connection.connect();
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }

        }
    });

Example

例子

采纳答案by Parnit

You are creating a method in your own click instead of calling the method. you should put the isConntectedToServer method in an asynctask and call the AsyncTask in the onClick

您是在自己的单击中创建一个方法,而不是调用该方法。您应该将 isConntectedToServer 方法放在 asynctask 中并在 onClick 中调用 AsyncTask

final Button mbutton = (Button) findViewById(R.id.httpcheck);
mbutton.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){

      //call asynctask containing isConntectedToServer method here

    }
});

//put this code in an asynctask and call it there
 public boolean isConnectedToServer(String url, int timeout) {
            try{
                URL myUrl = new URL("http://www.google.co.uk");
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(timeout);
                connection.connect();
                return true;
            } catch (Exception e) {
                return false;
            }
        }

回答by Joan Gil

Here you can find an answer of a similar question. You just have to change the function to make your function return a boolean. Hope that helps you.

在这里您可以找到类似问题的答案。您只需要更改函数即可使您的函数返回布尔值。希望能帮到你。

Test an HTTP connection

测试 HTTP 连接