Android网络编程---利用AsyncHttpClient自定义缓冲图片

来源:互联网 发布:淘宝上买精密管犯法么 编辑:程序博客网 时间:2024/05/16 14:21

网络编程:自定义缓冲图片-----------------获取服务器端的图片文件

该程序运行了loopj团队开源框架AsyncHttpClient

链接:https://github.com/loopj/android-async-http

/**
 * 自定义缓冲图片
 */
public class CacheImage extends Activity {

private ImageView iView;
private EditText eText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
iView = (ImageView) findViewById(R.id.iv);
eText = (EditText) findViewById(R.id.et_uri);
}

//一个button按钮的点击事件
public void showImage(View view){
String path = eText.getText().toString().trim();
getBitmap(path);
}
/**
* 根据网络路径得到图片------并进行缓冲
* @param path
*/
private void getBitmap(String path) {
try {
//新建一个缓冲文件---------由于文件名不能包含/所以用URLEncoder对其进行编码转换
final File cacheFile = new File(getCacheDir(),URLEncoder.encode(path, "UTF-8"));
AsyncHttpClient client = new AsyncHttpClient();
if (cacheFile.exists()) {
//设置请求头----------文件的最后修改时间If-Modified-Since是固定的格式
client.addHeader("If-Modified-Since", format(cacheFile.lastModified()));
}
client.get(path, new AsyncHttpResponseHandler() {

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (statusCode == 200) {
Bitmap bitmap = BitmapFactory.decodeByteArray(responseBody, 0, responseBody.length);
iView.setImageBitmap(bitmap);
}
try {
FileOutputStream fos = new FileOutputStream(cacheFile);
fos.write(responseBody);//将文件写入缓冲文件中
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
if (statusCode == 304) {
Bitmap bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
iView.setImageBitmap(bitmap);
}else {
Toast.makeText(CacheImage.this, "网络错误", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将long类型的时间转换为固定格式的时间
* @param ms
* @return
*/
private String format(long ms) {
Date date = new Date(ms);
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
String s = format.format(date);
return s;
}
}

0 0
原创粉丝点击