三、下载图片显示下载进度
package com.example.demo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {
private Handler handler;
public ImageLoadTask(Handler handler) {
this.handler = handler;
}
protected void onPostExecute(Bitmap result) {
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
}
protected Bitmap doInBackground(String... getUrls) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
// open connection
URL url = new URL(getUrls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int fileLength = urlConnection.getContentLength();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
inputStream = urlConnection.getInputStream();
byte data[] = new byte[4096];
long total = 0;
int count;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((count = inputStream.read(data)) != -1) {
total += count;
// publishing the progress....
if (fileLength > 0 && handler != null) {
handler.sendEmptyMessage(((int) (total * 100 / fileLength)) - 1);
}
output.write(data, 0, count);
}
ByteArrayInputStream bufferInput = new ByteArrayInputStream(output.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(bufferInput);
inputStream.close();
bufferInput.close();
output.close();
Log.i("image", "already get the image by uuid : " + getUrls[0]);
handler.sendEmptyMessage(100);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
总结:使用HttpURLConnection提交JSON数据的时候编码方式为UTF-8所有中文字符请一定要预先转码为UTF-8,然后在后台服务器对应的API中解码为UTF-8,不然就会报错HTTP 400。
以上就是本文的全部内容,希望对大家的学习Android软件编程有所帮助。










