简体   繁体   中英

IO exception in android

I am getting IO exception in following code. Please advise. I have added ** to the line where the exception is being caught. This is a webviewclient which downloads a file when clicked on the file link

public class MyWebViewClient extends WebViewClient {
    private String loginCookie;
    private Context mContext;
    private WebView mWebView;

    public MyWebViewClient(Context context, WebView webview) {
        super();

        mContext = context;
        mWebView = webview;
    }

    @Override
    public void onPageStarted( WebView view, String url, Bitmap favicon ) {
    }

    @Override
    public void onPageFinished( WebView view, String url ) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, loginCookie);
    }

    @Override
    public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
        Toast.makeText(view.getContext(), "ƒy�[ƒW“Ç‚�?�ž‚�?ƒGƒ‰�[", Toast.LENGTH_LONG).show();
        System.err.println(errorCode + " - " + description + "-" + failingUrl); 


    }



    @Override
    public void onLoadResource( WebView view, String url ){
        CookieManager cookieManager = CookieManager.getInstance();
        loginCookie = cookieManager.getCookie(url);
    }

    @Override
    public boolean shouldOverrideUrlLoading( WebView view, String url ) {


        if (url.contains(".pdf" )){
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
               .detectNetwork() // or .detectAll() for all detectable problems
               .penaltyDialog()  //show a dialog
               .permitNetwork() //permit Network access 
               .build());
            Toast.makeText(view.getContext(), "pdf", Toast.LENGTH_LONG).show();
            String savedFile=Download(url);


        }
        return false;
    }

    public String Download(String Url)
    {

     String filepath=null;
     try 
     {
      //set the download URL, a url that points to a file on the internet
      //this is the file to be downloaded
         final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
             public boolean verify1(String hostname, SSLSession session) {
                 return true;
             }

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                // TODO Auto-generated method stub
                return false;
            }
      };
         HttpURLConnection conn = null;
            URL url = new URL(Url);
            if (url.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

      //set up some things on the connection
      conn.setRequestMethod("GET");
      conn.setDoOutput(true); 
      //and connect!
      conn.connect();
      //set the path where we want to save the file
      //in this case, going to save it on the root directory of the
      //sd card.
      File SDCardRoot = Environment.getExternalStorageDirectory();
      //create a new file, specifying the path, and the filename
      //which we want to save the file as.

      String filename= "sample";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
      Log.i("Local filename:",""+filename);
      File file = new File(SDCardRoot,filename);
      if(file.createNewFile())
      {
       file.createNewFile();
      }

      //this will be used to write the downloaded data into the file we created
      FileOutputStream fileOutput = new FileOutputStream(file);


      //this will be used in reading the data from the internet
      InputStream inputStream = conn.getInputStream();


      //this is the total size of the file
      int totalSize = conn.getContentLength();
      //variable to store total downloaded bytes
      int downloadedSize = 0;


      //create a buffer...
      byte[] buffer = new byte[4 * 1024];
      int bufferLength = 0; //used to store a temporary size of the buffer


      //now, read through the input buffer and write the contents to the file
      while ( (bufferLength = inputStream.read(buffer)) > 0 )
      {
       //add the data in the buffer to the file in the file output stream (the file on the sd card
       fileOutput.write(buffer, 0, bufferLength);
       //add up the size so we know how much is downloaded
       downloadedSize += bufferLength;
       //this is where you would do something to report the prgress, like this maybe
       Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;


      }
      //close the output stream when done
      fileOutput.close();
      if(downloadedSize==totalSize)   filepath=file.getPath();

      //catch some possible errors...
     } catch (MalformedURLException e) {
      e.printStackTrace();
     } catch (IOException e) {
      filepath=null;
      e.printStackTrace();
     }
     **Log.i("filepath:is this error"," "+filepath) ;**


     return filepath;


    }







     private static void trustAllHosts() {
         // Create a trust manager that does not validate certificate chains
         TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return new java.security.cert.X509Certificate[] {};
                 }

                 public void checkClientTrusted(X509Certificate[] chain,
                                 String authType) throws CertificateException {
                 }

                 public void checkServerTrusted(X509Certificate[] chain,
                                 String authType) throws CertificateException {
                 }
         } };

         // Install the all-trusting trust manager
         try {
                 SSLContext sc = SSLContext.getInstance("TLS");
                 sc.init(null, trustAllCerts, new java.security.SecureRandom());
                 HttpsURLConnection
                                 .setDefaultSSLSocketFactory(sc.getSocketFactory());
         } catch (Exception e) {
                 e.printStackTrace();
         }
 }

        @Override
    public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
        handler.proceed();
    }

    @Override
    public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
        // ˆø��?host‚É‚�?setHttpAuthUsernamePassword‚Ì‘æ1ˆø��?‚Å��?’肵‚½•¶Žš—ñ‚ª“ü‚�?‚Ä‚«‚Ü‚·�B
        // Android 4.*�i‚à‚µ‚©‚·‚é‚Æ3.*‚©‚ç�j‚Å‚�?‚È‚º‚©ˆø��?host‚É�ŸŽè‚Ƀ|�[ƒg�?Ô�†‚ª’Ç‹L‚³‚ê‚Ä‚µ‚Ü‚¢‚Ü‚·�B
        // ‹ï‘Ì“I‚É‚�?�u:80�v‚ª’Ç‹L‚³‚ê‚Ä‚µ‚Ü‚¢‚Ü‚·�B

        String userName = null;
        String userPass = null;

        if (handler.useHttpAuthUsernamePassword() && view != null) {
            String[] haup = view.getHttpAuthUsernamePassword(host, realm);
            if (haup != null && haup.length == 2) {
                userName = haup[0];
                userPass = haup[1];
            }
        }

        if (userName != null && userPass != null) {
            handler.proceed(userName, userPass);
        }
        else {
            showHttpAuthDialog(handler, host, realm, null, null, null);
        }
    }

    private void showHttpAuthDialog( final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password ) {
        LinearLayout llayout = new LinearLayout((Activity)mContext);
        final TextView textview1 = new TextView((Activity)mContext);
        final EditText edittext1 = new EditText((Activity)mContext);
        final TextView textview2 = new TextView((Activity)mContext);
        final EditText edittext2 = new EditText((Activity)mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        textview1.setText("username:");
        textview2.setText("password:");
        llayout.addView(textview1);
        llayout.addView(edittext1);
        llayout.addView(textview2);
        llayout.addView(edittext2);

        final Builder mHttpAuthDialog = new AlertDialog.Builder((Activity)mContext);
        mHttpAuthDialog.setTitle("Enter your login details")
            .setView(llayout)
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    EditText etUserName = edittext1;
                    String userName = etUserName.getText().toString();
                    EditText etUserPass = edittext2;
                    String userPass = etUserPass.getText().toString();

                    mWebView.setHttpAuthUsernamePassword(host, realm, name, password);

                    handler.proceed(userName, userPass);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    handler.cancel();
                }
            })
            .create().show();
    }

}

Here is the logcat :

08-15 15:48:41.982: D/dalvikvm(14378): GC_FOR_ALLOC freed 1185K, 11% free 11443K/12743K, paused 76ms
08-15 15:48:41.982: I/dalvikvm-heap(14378): Grow heap (frag case) to 12.264MB for 1105936-byte allocation
08-15 15:48:42.052: D/dalvikvm(14378): GC_FOR_ALLOC freed 2K, 2% free 12521K/12743K, paused 57ms
08-15 15:48:42.192: D/dalvikvm(14378): GC_CONCURRENT freed 8K, 2% free 12513K/12743K, paused 7ms+3ms
08-15 15:48:42.192: D/webviewglue(14378): nativeDestroy view: 0x10a998
08-15 15:48:46.962: D/dalvikvm(14378): GC_CONCURRENT freed 1172K, 10% free 12501K/13831K, paused 1ms+2ms
08-15 15:49:01.962: W/System.err(14378): java.io.IOException: Hostname 'kee.mahindrasatyam.com' was not verified
08-15 15:49:01.962: W/System.err(14378):    at libcore.net.http.HttpConnection.verifySecureSocketHostname(HttpConnection.java:224)
08-15 15:49:01.962: W/System.err(14378):    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:445)
08-15 15:49:01.972: W/System.err(14378):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
08-15 15:49:01.972: W/System.err(14378):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
08-15 15:49:01.972: W/System.err(14378):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
08-15 15:49:01.972: W/System.err(14378):    at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
08-15 15:49:01.972: W/System.err(14378):    at com.example.techmkmsworld.MyWebViewClient.Download(MyWebViewClient.java:138)
08-15 15:49:01.972: W/System.err(14378):    at com.example.techmkmsworld.MyWebViewClient.shouldOverrideUrlLoading(MyWebViewClient.java:97)
08-15 15:49:01.972: W/System.err(14378):    at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:224)
08-15 15:49:01.972: W/System.err(14378):    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:324)
08-15 15:49:01.972: W/System.err(14378):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 15:49:01.972: W/System.err(14378):    at android.os.Looper.loop(Looper.java:137)
08-15 15:49:01.982: W/System.err(14378):    at android.app.ActivityThread.main(ActivityThread.java:4448)
08-15 15:49:01.982: W/System.err(14378):    at java.lang.reflect.Method.invokeNative(Native Method)
08-15 15:49:01.982: W/System.err(14378):    at java.lang.reflect.Method.invoke(Method.java:511)
08-15 15:49:01.982: W/System.err(14378):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-15 15:49:01.982: W/System.err(14378):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-15 15:49:01.992: W/System.err(14378):    at dalvik.system.NativeStart.main(Native Method)
08-15 15:49:01.992: I/filepath:is this error(14378):  null

OK then, this java.io.IOException: Hostname 'kee.mahindrasatyam.com' was not verified cause the IOException and as I saw this:

final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
             public boolean verify1(String hostname, SSLSession session) {
                 return true;
             }

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                // TODO Auto-generated method stub
                return false;
            }
      };

Seems like you have an extra verify1 which is no used. Instead the @Override verify return false , so your host will NOT be verified leading to the problem. Please remove verify1 and in verify return true .

UPDATE : For your FileNotFoundException , please make sure your add the permission in AndroidManifest.xml :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And check whether the file exist after adding:

file.createNewFile();
if(file.exists()){
// It's ok to continue
}else{
    // Handle here first
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM