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

时间:2014-05-13 04:52:38

标签: android url file-exists android-internet

我希望我的Android程序使用其URL检查远程服务器中是否存在文件(例如index.php)。即如果我点击按钮,它应检查是否存在网址。如果是,它应该加载相同的URL,否则显示一条消息"文件不存在!"

我做了类似的事情:

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

    }
};

/ *这是要调用的函数来检查index.php文件是否存在或是否已根据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;
    }
  }

但是,即使文件确实存在于指定的文件夹中,这总是会给我一个错误的返回值。只是绝望的尝试,我尝试显示con.getResponsecode()的值,它总是给我一个0值。任何人都可以帮助我,为什么输出表现得像这样?

1 个答案:

答案 0 :(得分:5)

我相信你是在主线程中这样做的。这就是它无法正常工作的原因,你无法在主线程中执行网络操作。

尝试将代码放入AsyncTask或Thread。

编辑1:作为快速修复,请尝试包装“文件检查代码”,如下所示:

    new Thread() {

        public void run() {
        //your "file checking code" goes here like this
        //write your results to log cat, since you cant do Toast from threads without handlers also...

      try {
         HttpURLConnection.setFollowRedirects(false);
         // note : you may also need
         //HttpURLConnection.setInstanceFollowRedirects(false)

         HttpURLConnection con =  (HttpURLConnection) new URL(URLName).openConnection();
         con.setRequestMethod("HEAD");
         if( (con.getResponseCode() == HttpURLConnection.HTTP_OK) ) 
            log.d("FILE_EXISTS", "true");
         else 
            log.d("FILE_EXISTS", "false");
 }
              catch (Exception e) {
                e.printStackTrace();
               log.d("FILE_EXISTS", "false");;
           }
             }
      }.start();