检查服务器上是否存在URL

时间:2014-10-17 05:34:56

标签: android url android-asynctask thread-safety file-exists

这是我用来验证的代码,在服务器上存在或不存在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;
        }
    }

}

5 个答案:

答案 0 :(得分:14)

您将获得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);
    }

答案 1 :(得分:1)

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;
   }

答案 2 :(得分:0)

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

    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, 

如果你这样做,就会有异常,你无法得到正确的结果。     因此,如果您希望应用程序执行网络操作,您可以使用另一个线程来执行此操作。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

示例:

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