android 下载文件HttpURLConnection.getContentLength()为0,不下载

下载的时候,莫名奇妙的不能下载在本地。如图下边

HttpURLConnection conn = null;
			RandomAccessFile raf = null;
			try {
				URL url = new URL(mFileInfo.getUrl());
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestMethod("GET");
				int code = conn.getResponseCode();
				int length = -1;
				if (code == HttpURLConnection.HTTP_OK) {
					length = conn.getContentLength();
				}
				if (length <= 0) {
					return;
				}
				File dir = new File(DownloadPath);
				if (!dir.exists()) {
					dir.mkdir();
				}
				File file = new File(dir, mFileInfo.getFileName());
				raf = new RandomAccessFile(file, "rwd");
				raf.setLength(length);
				mFileInfo.setLength(length);
				Message msg = Message.obtain();
				msg.obj = mFileInfo;
				msg.what = MSG_INIT;
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (conn != null) {
					conn.disconnect();
				}
				try {
					if (raf != null) {
						raf.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

经过断点发现会走这步

if (length <= 0) {
	return;
}

此时length 是为0,为什么会为0呢?

	if (code == HttpURLConnection.HTTP_OK) {
		length = conn.getContentLength();
	 }

getContentLength()是没有获取到
然后添加一行
conn.setRequestProperty(“Accept-Encoding”, “identity”);

因为Accept-Encoding:HTTP请求头,标识客户端能够理解的内容编码方式,通常是一种压缩算法,如:gizp,deflate,compress,identity… 客户端向服务端发送该请求头,示意服务端如果需要编码只能用这些编码方式,当然也有可以不用。无论用还是不用,服务端需要在响应头中加入Content-Encoding,其中identity标识未使用编码

可以解决getContentLength()为0,没有下载的问题。

如有不对的欢迎评论

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
欢迎!以下是一个简单的Android下载文件的代码示例: 首先,在AndroidManifest.xml文件中添加网络权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 然后,在Activity中创建一个异步任务类来处理下载: ```java import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class DownloadTask extends AsyncTask<String, Integer, String> { private ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle("下载文件"); progressDialog.setMessage("正在下载,请稍候..."); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.show(); } @Override protected String doInBackground(String... params) { String fileUrl = params[0]; String savePath = Environment.getExternalStorageDirectory().getPath() + "/downloaded_file.jpg"; try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream inputStream = connection.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(savePath); byte[] buffer = new byte[1024]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { totalBytesRead += bytesRead; publishProgress((int) ((totalBytesRead * 100) / fileLength)); fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); inputStream.close(); connection.disconnect(); } catch (Exception e) { Log.e("DownloadTask", e.getMessage()); return "下载失败"; } return "下载成功"; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); progressDialog.setProgress(progress[0]); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressDialog.dismiss(); Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); } } ``` 最后,在需要下载文件的地方调用AsyncTask执行下载任务: ```java String fileUrl = "http://example.com/file.jpg"; new DownloadTask().execute(fileUrl); ``` 以上代码实现了一个可以下载文件的简单Android应用。它使用了一个异步任务类来执行网络请求并将文件保存到设备的指定路径中。显示了一个进度对话框来显示下载进度,并在下载完成后显示一个Toast消息。请注意,这个示例仅供参考,实际应用可能需要进一步处理异常、权限检查等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值