Asynchttpclient开源框架下载图片和文本,于Volley和Glide开源框架的区别。

时间:2024-01-20 21:55:51

AsyncHttpClient是一款比较流行的Android异步网路加载库,在github上的网址是:https://github.com/loopj/android-async-http
AsyncHttpClient和开源框架 Volley和Glide不同的是,不像Volley和Glide内部已经实现好了缓存策略,AsyncHttpClient自身没有实现缓存策略。

代码如下:

 package com.lixu.asynchttpclient;

 import org.apache.http.Header;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity {
private TextView tv;
private ImageView iv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); iv = (ImageView) findViewById(R.id.iv);
// 文本和图片的网络地址
String url1 = "http://www.baidu.com"; String url2 = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1183223528,3058066243&fm=116&gp=0.jpg"; loadtxt(url1); loadimage(url2); } private void loadtxt(String url1) {
// 创建AsyncHttpClient对象
AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(url1, new AsyncHttpResponseHandler() { @Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
Toast.makeText(getApplicationContext(), "错误!!", 0).show();
} @Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// 将获取到的byte[]数组转换成String字符串
tv.setText(new String(arg2));
}
});
} private void loadimage(String url2) { AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(url2, new AsyncHttpResponseHandler() { @Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) { Toast.makeText(getApplicationContext(), "错误!!", 0).show();
} @Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// 创建bitmap图片工厂
BitmapFactory bf = new BitmapFactory();
// 用图片工厂将字节数组转换成bitmap图片
Bitmap bitmap = bf.decodeByteArray(arg2, 0, arg2.length); iv.setImageBitmap(bitmap); } }); }
}

xml文件:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" > <TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView> <ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" /> </LinearLayout>

运行效果:

Asynchttpclient开源框架下载图片和文本,于Volley和Glide开源框架的区别。