<LinearLayout
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:orientation="vertical"
tools:context="org.mobiletrain.a7_3volley.MainActivity"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="getString1"
android:text="请求字符串"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="getJsonObject"
android:text="请求一个Json数据"/> <TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity { private RequestQueue queue;
private TextView tv;
private ImageView iv;
private String imageUrl; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageUrl = "http://a.hiphotos.baidu.com/news/q%3D100/sign=e5edcefd9558d109c2e3adb2e159ccd0/0ff41bd5ad6eddc4696319783edbb6fd536633a8.jpg";
queue = Volley.newRequestQueue(this);
tv = ((TextView) findViewById(R.id.tv));
iv = ((ImageView) findViewById(R.id.iv));
} public void getString1(View view) {
//如果不指定请求方式,默认为Get请求
StringRequest request = new StringRequest("http://www.baidu.com", new Response.Listener<String>() {
//当请求成功时回调该方法
@Override
public void onResponse(String response) {
tv.setText(response);
Log.d("lenve", "onResponse: response:" + response);
}
}, new Response.ErrorListener() {
//请求失败时回调
@Override
public void onErrorResponse(VolleyError error) { }
});
//将请求添加到队列中去
queue.add(request);
} public void getJsonObject(View view) {
//第二参数表示传递给服务器的参数,如果第二参数为null,即不需要给服务端传递参数,此时的请求方式为get请求,否则为post请求
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://www.tngou.net/api/food/classify", null, new Response.Listener<JSONObject>() {
//请求成功时回调的方法
@Override
public void onResponse(JSONObject response) {
StringBuffer result = new StringBuffer();
try {
JSONArray tngou = response.getJSONArray("tngou");
for (int i = 0; i < tngou.length(); i++) {
result.append(tngou.getJSONObject(i).getString("name") + "\n");
}
tv.setText(result.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) { }
});
queue.add(jsonObjectRequest);
} public void getJsonArray(View view) {
//请求JsonArray数据
JsonArrayRequest arrayRequest = new JsonArrayRequest("http://www.tngou.net/api/food/classify", new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("lenve", "onResponse: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("lenve", "onErrorResponse: error:" + error.getMessage());
}
});
queue.add(arrayRequest);
} public void getImage(View view) {
//1.图片地址
//2.图片加载成功的回调
//3.图片的最大宽度
//4.图片的最大高度
//5.图片缩放模仿
//6.加载图片的色彩模式
//7.加载失败时的回调
ImageRequest imageRequest = new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
iv.setImageBitmap(response);
}
}, 200, 200, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) { }
});
queue.add(imageRequest);
} public void imageloader(View view) {
BitmapCache imageCache = new BitmapCache(this);
//1.请求队列
//2.图片缓存工具类
ImageLoader imageLoader = new ImageLoader(queue, imageCache);
//1.显示下载图片的ImageView控件
//2.默认图片
//3.下载出错时显示的图片
ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(iv, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
//1.请求的图片地址
//2.监听器
imageLoader.get(imageUrl, imageListener);
}
}
public class BitmapCache implements ImageLoader.ImageCache { private LruCache<String, Bitmap> lruCache;
private Context context; public BitmapCache(Context context) {
this.context = context;
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int maxSize = maxMemory / 8;
lruCache = new LruCache<String, Bitmap>(maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
} @Override
public Bitmap getBitmap(String url) {
Bitmap bitmap = lruCache.get(subUrl(url));
if (bitmap != null) {
return bitmap;
} else {
bitmap = getBitmapFromSDCard(subUrl(url));
if (bitmap != null) {
lruCache.put(subUrl(url), bitmap);
}
return bitmap;
}
} private Bitmap getBitmapFromSDCard(String s) {
return BitmapFactory.decodeFile(context.getExternalCacheDir().getAbsolutePath() + File.separator + s);
} private String subUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1, url.length());
} @Override
public void putBitmap(String url, Bitmap bitmap) {
lruCache.put(subUrl(url), bitmap);
saveBitmap2SDCard(subUrl(url), bitmap);
} private void saveBitmap2SDCard(String url, Bitmap bitmap) {
//如果SD卡中已经有了图片,则不需要再保存
Bitmap bitmapFromSDCard = getBitmapFromSDCard(url);
if (bitmapFromSDCard != null) {
return;
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(context.getExternalCacheDir(), url)));
if (url.toLowerCase().contains(".png")) {
//如果第一个参数为PNG,第二个参数无意义
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
} else {
//如果第一个参数为JPEG,则第二个参数会影响图片的质量,第二个参数取值(0~100),值越大,图片质量越高
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
使用步骤:
第一步:创建请求队列(一般创建一次即可)RequestQueue mQueue = Volley.newRequestQueue(this);
第二步:根据业务需要创建一个请求
StringRequest sr = new StringRequest(XXX);
JsonObjectRequest jsonReq = new JsonObjectRequest(XXX);
JsonArrayRequest arrayRequest = new JsonArrayRequest(XXX);
ImageRequest imageRequest = new ImageRequest(XXX); ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
ImageListener listener = ImageLoader.getImageListener(imageView,
R.drawable.ic_launcher, R.drawable.ic_launcher);
imageLoader.get(IMAGEURL, listener); ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
networkImageView.setImageUrl(IMAGEURL,imageLoader);
第三步:将请求加入到请求队列中
mQueue.add(对象);
Volley和Okhttp的区别
Volley支持并发网络连接,支持同时取消单个或多个请求,还可以轻松的发送异步请求来填充UI数据。拥有请求任务队列管理,适合小而频繁的请求。对于请求大数据,比如下载文件,Volley不太合适
Okhttp使用线程池技术减少请求的延迟,无缝的支持GZIP来减少数据流量,缓存响应数据来减少重复的网络请求。而且弥补了Volley的不足,比如,Volley默认不支持文件的上传,而Okhttp提供了多文件上传功能
Okhttp缺点:消息回来需要切到主线程,主线程要自己去写,第二传入调用比较复杂