检查服务器上是不是存在 URL

Posted

技术标签:

【中文标题】检查服务器上是不是存在 URL【英文标题】:Check if URL exists or not on Server检查服务器上是否存在 URL 【发布时间】:2014-12-12 15:38:06 【问题描述】:

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

我在代码中出错的地方,为什么我总是得到“不存在!”

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";
        boolean bResponse = exists(customURL);

        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();
           

    

    public static boolean exists(String URLName)
        try 
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection con =  (HttpURLConnection) new URL(URLName).openConnection();
            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        
        catch (Exception e) 
            e.printStackTrace();
            return false;
        
    


【问题讨论】:

***.com/questions/1378199/… @NaveenTamrakar 尝试仍然得到“不存在!” 在exist function HttpURLConnection.setFollowRedirects(false)中去掉这个; 只需添加con.connect() about return 声明.. @ashutiwari4 尚未完成 【参考方案1】:

你会得到Network On Main Thread Exception

看NetworkOnMainThreadException

所以你的方法总是返回 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();
                                  
                   
    

使用 ScheduledThreadPoolExecutor:

但记得关闭它!

public class MainActivity extends Activity 
     String customURL;
     String msg = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

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

        final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
        myTimer.scheduleAtFixedRate(new Runnable() 

            @Override
            public void run() 

                try 
                    HttpURLConnection.setFollowRedirects(false);
                    HttpURLConnection con =  (HttpURLConnection) new URL(customURL).openConnection();
                    con.setRequestMethod("HEAD");
                    System.out.println(con.getResponseCode()); 

                    if(con.getResponseCode() == HttpURLConnection.HTTP_OK)

                        msg = "File exist!";

                    else

                        msg = "File does not exist!";

                    

                    runOnUiThread(new Runnable() 

                            @Override
                            public void run() 

                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();      
                            
                        );
                
                catch (Exception e)    
                    e.printStackTrace();    
                    return;
                

            
        , 0,10000, TimeUnit.MILLISECONDS);
    

【讨论】:

非常感谢你能帮我对现有代码做一个小的修改吗,因为我必须每 10 秒检查一次这个链接,所以你能对此进行更改 该任务的编写器计时器。每次@Sophie 都会调用这个 asytask 我想检查一次。有替代品吗? 似乎它只适用于图像或 Mp3 等文件 url。我正在尝试https://app.box.com/s/w6quybg71ngjhetflz77,但没有工作说链接不存在【参考方案2】:

把你的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;
   

【讨论】:

你应该总是使用 AsynckTask【参考方案3】:

使用if(bResponse) 代替if(bResponse==true)

【讨论】:

【参考方案4】:

你可以使用下面的代码来试试。

    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, 

如果这样做,将会出现异常并且您无法获得正确的结果。 因此,如果您希望应用程序执行网络操作,您可以使用另一个线程来执行它。

【讨论】:

【参考方案5】:

我使用此代码来验证 url 是否有效。我已经用图片网址测试了这段代码

例子:

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());
    

【讨论】:

以上是关于检查服务器上是不是存在 URL的主要内容,如果未能解决你的问题,请参考以下文章

Android 使用其 URL 检查文件是不是存在于远程服务器中

检查xml(没有文件扩展名)是不是存在的最佳方法

用 R 检查远程目录是不是存在

如何检查 FTP 服务器上是不是存在文件?

检查Java中服务器上是不是存在路径[重复]

如何检查服务器上是不是存在任何pdf文件?