在我的应用程序中,我写了simole下载管理器,通过互联网下载文件。但是HttpURLConnection getContentLength()
会返回错误的结果,例如-1
,我正在测试this image文件。文件存在,并没有问题,但我有问题,以获得文件大小。我的简化代码:
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
final int fileSize = connection.getContentLength();
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
int downloadedSize = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;
if (listener != null) {
}
}
outputStream.close();
connection.disconnect();
权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
答案 0 :(得分:0)
您的代码中的主要问题似乎是对connection.setDoOutput(true);
的调用。
包含该调用后,我从getContentLength()获得了-1
的返回值,并且它也没有成功下载图像。
当我删除对connection.setDoOutput(true);
的调用时,它开始工作正常并返回有效值,并且还成功下载了图像。
以下代码对我有用,我在下载完成后添加了代码以显示返回值getContentLength()
的祝酒词:
class PostAsync extends AsyncTask<String, String, Integer> {
private ProgressDialog pDialog;
private static final String sourcepath = "http://www.planwallpaper.com/static/images/supranatural-3d-wallpaper-images.jpg";
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting download...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Integer doInBackground(String... args) {
int fileSize = 0;
try {
URL url = new URL(sourcepath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
fileSize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
bmp = BitmapFactory.decodeStream(inputStream);
inputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return fileSize;
}
protected void onPostExecute(Integer fileSize) {
pDialog.dismiss();
MainActivity.this.image.setImageBitmap(bmp);
Toast.makeText(MainActivity.this, "file size: " + fileSize, Toast.LENGTH_LONG).show();
}
}
我测试了两个不同的图像,以确保它返回不同的值。
首先,问题中的图片是:
使用不同的图像:
完整的MainActivity类:
public class MainActivity extends ActionBarActivity {
private ImageView image;
private Bitmap bmp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
new PostAsync().execute();
}
@Override
protected void onResume() {
super.onResume();
//put on resume functionality here....
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PostAsync extends AsyncTask<String, String, Integer> {
private ProgressDialog pDialog;
private static final String sourcepath = "http://www.planwallpaper.com/static/images/supranatural-3d-wallpaper-images.jpg";
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting download...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Integer doInBackground(String... args) {
int fileSize = 0;
try {
URL url = new URL(sourcepath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
fileSize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
bmp = BitmapFactory.decodeStream(inputStream);
inputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return fileSize;
}
protected void onPostExecute(Integer fileSize) {
pDialog.dismiss();
MainActivity.this.image.setImageBitmap(bmp);
Toast.makeText(MainActivity.this, "file size: " + fileSize, Toast.LENGTH_LONG).show();
}
}
}
activity_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView android:id="@+id/imageView" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>