I want my Android program to check if file (e.g. index.php) exists in a remote server using its URL. i.e. if I click the button, it should check if a url exists. If it does, it should load that same URL otherwise display a message "File does not exist!"
I did something like this:
private OnClickListener cameraListener9=new OnClickListener(){
public void onClick(View v){
idNo=editText.getText().toString();
String URLName ="http://blahblah/kufpt/upload_test/"+ idNo + "/index.php";
boolean bResponse = exists(URLName);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "FILE EXISTS" , Toast.LENGTH_SHORT).show();
WebView mWebView =(WebView)findViewById(R.id.webView);
mWebView.loadUrl(URLName);
}
else
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
};
/* this is the function to be called to check if index.php file exists or has been created */ as suggested in Check if file exists on remote server using its URL
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
But, this always give me a false return value even if the file really does exists in the specified folder. Just a desperate attempt, I tried displaying the value of con.getResponsecode(), it always gives me a 0 value. Anybody could help me why is the output behaving like this?