gpt4 book ai didi

java - 检查与 URL 的 HTTP 连接 (Android)

转载 作者:可可西里 更新时间:2023-11-01 17:02:21 24 4
gpt4 key购买 nike

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

过程:

用户点击按钮,应用程序发送一个获取请求,如果成功则返回 true,否则返回 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

最佳答案

您是在自己的点击中创建一个方法,而不是调用该方法。您应该将 isConntectedToServer 方法放在异步任务中,并在 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;
}
}

关于java - 检查与 URL 的 HTTP 连接 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443853/

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