Volley网络通讯框架

<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(); } } } } }

 使用步骤:android

第一步:建立请求队列(通常建立一次便可)RequestQueue mQueue = Volley.newRequestQueue(this); 
第二步:根据业务须要建立一个请求json

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(对象);api

Volley和Okhttp的区别缓存

Volley支持并发网络链接,支持同时取消单个或多个请求,还能够轻松的发送异步请求来填充UI数据。拥有请求任务队列管理,适合小而频繁的请求。对于请求大数据,好比下载文件,Volley不太合适服务器

Okhttp使用线程池技术减小请求的延迟,无缝的支持GZIP来减小数据流量,缓存响应数据来减小重复的网络请求。并且弥补了Volley的不足,好比,Volley默认不支持文件的上传,而Okhttp提供了多文件上传功能网络

Okhttp缺点:消息回来须要切到主线程,主线程要本身去写,第二传入调用比较复杂并发

相关文章
相关标签/搜索