使用移动网络时无法下载apk

时间:2017-08-03 09:50:16

标签: android httpurlconnection download-manager

当我使用wifi下载apk时,这是正常的。这是我的代码:

  private void singleDownloadThread() {
    try {
        URL url = new URL(entity.getUrl());
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(CONNECT_TIME);
        connection.setReadTimeout(READ_TIME);
        FileOutputStream fos = new FileOutputStream(entity.getPath());
        InputStream is = connection.getInputStream();
        byte[] buffer = new byte[2048];
        int len = -1;
        long contentlength = connection.getContentLength();
        entity.setSize((int) contentlength);
        while ((len = is.read(buffer)) != -1) {
            entity.setProgress(entity.getProgress() + len);
            L.e("len:"+len+",projress:"+entity.getProgress()+",length:"+contentlength);
            Message msg = mHandler.obtainMessage();
            msg.what = ConstantValues.Download.UPDATA_DOWNLOAD_PROGRESS;
            msg.obj = entity;
            mHandler.sendMessage(msg);
            fos.write(buffer, 0, len);
        }
        entity.setStatus(DownloadStatus.done);
        Message msg = mHandler.obtainMessage();
        msg.what = ConstantValues.Download.DOWNLOAD_DONE;
        msg.obj = entity;
        mHandler.sendMessage(msg);

        is.close();
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        entity.setStatus(DownloadStatus.netError);
        Message msg = mHandler.obtainMessage();
        msg.what = ConstantValues.Download.DOWNLOAD_ERROR;
        msg.obj = entity;
        mHandler.sendMessage(msg);
    }
}

在移动网络中进行下载时,最终是java.net.SocketTimeoutException,但我可以在开始时下载一点。然后,控制台打印异常:

 W/System.err: java.net.SocketTimeoutException: timeout
W/System.err:     at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:212)
W/System.err:     at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:250)
W/System.err:     at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:217)
W/System.err:     at com.android.okhttp.okio.RealBufferedSource.read(RealBufferedSource.java:50)
W/System.err:     at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:418)
W/System.err:     at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:371)
W/System.err:     at java.io.InputStream.read(InputStream.java:101)

0 个答案:

没有答案