Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 检查服务器上是否存在URL_Android_Url_Android Asynctask_Thread Safety_File Exists - Fatal编程技术网

Android 检查服务器上是否存在URL

Android 检查服务器上是否存在URL,android,url,android-asynctask,thread-safety,file-exists,Android,Url,Android Asynctask,Thread Safety,File Exists,这是我的代码,我用它来验证,URL是否存在于服务器上,但总是不存在,但链接是活动的 我在代码中犯了错误,为什么我总是得到“不存在!” 将您的exists()更改为此 public boolean exists(String url){ HttpURLConnection huc = ( HttpURLConnection ) url.openConnection (); huc.setRequestMethod ("GET"); //OR huc.setRequestM

这是我的代码,我用它来验证,URL是否存在于服务器上,但总是不存在,但链接是活动的

我在代码中犯了错误,为什么我总是得到“不存在!”

将您的exists()更改为此

public boolean exists(String url){
    HttpURLConnection huc =  ( HttpURLConnection )  url.openConnection (); 
    huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
    huc.connect () ; 
    int code = huc.getResponseCode() ;
    System.out.println(code);

     if(code==200)
       return true;
     else
    return false;
   }

您将在主线程上获得
网络异常

因此,您的方法总是返回false,因为:

   catch (Exception e) {
        e.printStackTrace();
        return false;
    }
快速修复:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

        MyTask task = new MyTask();
        task.execute(customURL);
    }


    private class MyTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Boolean doInBackground(String... params) {

             try {
                    HttpURLConnection.setFollowRedirects(false);
                    HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();
                    con.setRequestMethod("HEAD");
                    System.out.println(con.getResponseCode()); 
                    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
                }
                catch (Exception e) {   
                    e.printStackTrace();    
                    return false;
                }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            boolean bResponse = result;
             if (bResponse==true)
                {
                    Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();      
                }
                else
                {           
                    Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
                }                  
        }           
    }
}

您可以使用以下代码进行尝试

    final String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
            new Thread(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    super.run();
                    try {
                        URL url = new URL(customURL);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("HEAD");
                        con.connect();
                        Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
                        if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
                            Log.i(TAG, "Sucess");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i(TAG, "fail");
                    }
                }

            }.start();

Reason: After android 2.3, you can't perform a networking operation on its main thread, 
如果您这样做,将出现can异常,您无法获得正确的结果。
因此,如果您希望应用程序执行联网操作,可以使用另一个线程来执行。

使用
if(breresponse)
而不是
if(breresponse==true)

我使用此代码验证url是否处于活动状态。我已经用图像url测试了这段代码

例如:

url = "https://ima.vn/wp-content/uploads/2017/11/ima-sofa-titan-trungkinh-1-of-3.jpg"
message = "Image url";

@Naveentamakar仍尝试获取“不存在!”删除存在函数HttpURLConnection中的此项。setFollowRedirects(false);只需添加
con.connect()
about
return
statement..@ashutiwari4还不知道您能为我对现有代码做一个小的修改吗?因为我必须每10秒钟检查一次这个链接,所以您能为该任务更改writer计时器吗。每次@SophieI想要检查一次,它都会将此任务称为asytask。有其他选择吗?似乎它只适用于文件url,如图像或Mp3等。我正在尝试
https://app.box.com/s/w6quybg71ngjhetflz77
但如果不使用它,则表示链接不存在您应该始终使用AsynckTask
    final String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
            new Thread(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    super.run();
                    try {
                        URL url = new URL(customURL);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("HEAD");
                        con.connect();
                        Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
                        if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
                            Log.i(TAG, "Sucess");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i(TAG, "fail");
                    }
                }

            }.start();

Reason: After android 2.3, you can't perform a networking operation on its main thread, 
url = "https://ima.vn/wp-content/uploads/2017/11/ima-sofa-titan-trungkinh-1-of-3.jpg"
message = "Image url";
public void assertUrlalive(String url, String message) {
    try {
        URL myUrl = new URL(url);
        HttpURLConnection huc = (HttpURLConnection) myUrl.openConnection();
        assertEquals(huc.getResponseCode(), 200, message);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("Connection Err: " + e.getMessage());
    }
}