Check if URL exists or not on Server
Asked Answered
F

5

7

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 I am always getting "doesnot exist !"

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

}
Fachini answered 17/10, 2014 at 5:34 Comment(11)
#1378699Kerbing
@NaveenTamrakar tried still getting "does not exists !"Fachini
remove this in exist function HttpURLConnection.setFollowRedirects(false);Amphitropous
just add con.connect() about return statement ..Tripartition
@ashutiwari4 yet not doneFachini
@Tripartition can you show me where?Fachini
after con.setRequestMethod("HEAD"); line add con.connect()Tripartition
@Tripartition can you try this at your end, because still getting does not existsFachini
I have tried at my end and i am getting 200response..can you please Log con.getResponseCode() at your end?Tripartition
@Tripartition getting nothing can you share your method with me ?Fachini
check this : pastebin.com/hxDMWJFBTripartition
F
14

You will get Network On Main Thread Exception

Look at NetworkOnMainThreadException

so your method always returns false because of:

   catch (Exception e) {
        e.printStackTrace();
        return false;
    }

quick fix:

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

With a ScheduledThreadPoolExecutor:

but remember to shut down it!!

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);
    }
Ferdinana answered 17/10, 2014 at 6:16 Comment(4)
thank you so much can you do a small modification in existing code for me, because i have to check for this link in every 10 seconds, so can you make changes for thatFachini
writer timer for that task . it will call this asytask everytime @FachiniHajji
I want to check for one time. Any alternate?Anorthosite
Seems it will work only for file url like image or Mp3 and so on. I was trying for https://app.box.com/s/w6quybg71ngjhetflz77 but not working it saying link not existNucleolated
G
1

Change your exists() to this

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;
   }
Genevagenevan answered 17/10, 2014 at 5:42 Comment(1)
you should always use AsynckTaskIntermit
V
1

Use if(bResponse) instead of if(bResponse==true)

Vorster answered 7/2, 2017 at 5:28 Comment(0)
F
0

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.

Faxun answered 17/10, 2014 at 6:36 Comment(0)
C
0

I use this code to verify url alive. I have tested this code with image url

Example:

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());
    }
}
Crinkle answered 25/2, 2020 at 2:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.