Check if URL exists or not on Server

后端 未结 5 926
失恋的感觉
失恋的感觉 2020-12-18 00:48

This is my code which I am using to verify, URL exists or not on Server, but always getting not exist however link is alive

Where I am doing mistake in my code, why

5条回答
  •  被撕碎了的回忆
    2020-12-18 01:45

    you can use the follow code to try.

        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, 
    

    if you do so, there will be can exception and you can't get the right result. So if you want the application to perform a networking operation, you can use another Thread to do it.

提交回复
热议问题