Making a Standard Request

1.This lesson teaches you to

  1. Request a String  返回String
  2. Request an Image  返回Image
  3. Request JSON     返回Json

VIDEO

  Volley: Easy, Fast Networking for Android

  This lesson describes how to use the common request types that Volley supports:

  • StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
  • ImageRequest. Specify a URL and receive an image in response.
  • JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.

  If your expected response is one of these types, you probably won't have to implement a custom request. This lesson describes how to use these standard request types. For information on how to implement your own custom request, see Implementing a Custom Request.

2.Request a String

 String url ="http://www.myurl.com";

 // Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}); // Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);

3.Request an Image

3.1 简介

  Volley offers the following classes for requesting images. These classes layer on top of each other to offer different levels of support for processing images:

  • ImageRequest—a canned request for getting an image at a given URL and calling back with a decoded bitmap. It also provides convenience features like specifying a size to resize to. Its main benefit is that Volley's thread scheduling ensures that expensive image operations (decoding, resizing) automatically happen on a worker thread.
  • ImageLoader—a helper class that handles loading and caching images from remote URLs. ImageLoaderis a an orchestrator for large numbers of ImageRequests, for example when putting multiple thumbnails in a ListViewImageLoader provides an in-memory cache to sit in front of the normal Volley cache, which is important to prevent flickering. This makes it possible to achieve a cache hit without blocking or deferring off the main thread, which is impossible when using disk I/O. ImageLoader also does response coalescing, without which almost every response handler would set a bitmap on a view and cause a layout pass per image. Coalescing makes it possible to deliver multiple responses simultaneously, which improves performance.
  • NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.

3.2 Use ImageRequest

  Here is an example of using ImageRequest. It retrieves the image specified by the URL and displays it in the app. Note that this snippet interacts with the RequestQueue through a singleton class (see Setting Up a RequestQueue for more discussion of this topic):

 ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
... // Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, , , null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);

3.3 Use ImageLoader and NetworkImageView

  You can use ImageLoader and NetworkImageView in concert to efficiently manage the display of multiple images, such as in a ListView. In your layout XML file, you use NetworkImageView in much the same way you would use ImageView, for example:

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="150dp"
android:layout_height="170dp"
android:layout_centerHorizontal="true" />

  You can use ImageLoader by itself to display an image, for example:

 ImageLoader mImageLoader;
ImageView mImageView;
// The URL for the image that is being loaded.
private static final String IMAGE_URL =
"http://developer.android.com/images/training/system-ui.png";
...
mImageView = (ImageView) findViewById(R.id.regularImageView); // Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();
mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,
R.drawable.def_image, R.drawable.err_image));

  However, NetworkImageView can do this for you if all you're doing is populating an ImageView. For example:

 ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
"http://developer.android.com/images/training/system-ui.png";
... // Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView); // Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader(); // Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

  The above snippets access the RequestQueue and the ImageLoader through a singleton class, as described in Setting Up a RequestQueue. This approach ensures that your app creates single instances of these classes that last the lifetime of your app. The reason that this is important for ImageLoader (the helper class that handles loading and caching images) is that the main function of the in-memory cache is to allow for flickerless rotation. Using a singleton pattern allows the bitmap cache to outlive the activity. If instead you create theImageLoader in an activity, the ImageLoader would be recreated along with the activity every time the user rotates the device. This would cause flickering.

3.4 Example LRU cache

  The Volley toolbox provides a standard cache implementation via the DiskBasedCache class. This class caches files directly onto the hard disk in the specified directory. But to use ImageLoader, you should provide a custom in-memory LRU bitmap cache that implements the ImageLoader.ImageCache interface. You may want to set up your cache as a singleton; for more discussion of this topic, see Setting Up a RequestQueue.

  Here is a sample implementation for an in-memory LruBitmapCache class. It extends the LruCache class and implements the ImageLoader.ImageCache interface:

 import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import com.android.volley.toolbox.ImageLoader.ImageCache; public class LruBitmapCache extends LruCache<String, Bitmap>
implements ImageCache { public LruBitmapCache(int maxSize) {
super(maxSize);
} public LruBitmapCache(Context ctx) {
this(getCacheSize(ctx));
} @Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
} @Override
public Bitmap getBitmap(String url) {
return get(url);
} @Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
} // Returns a cache size equal to approximately three screens worth of images.
public static int getCacheSize(Context ctx) {
final DisplayMetrics displayMetrics = ctx.getResources().
getDisplayMetrics();
final int screenWidth = displayMetrics.widthPixels;
final int screenHeight = displayMetrics.heightPixels;
// 4 bytes per pixel
final int screenBytes = screenWidth * screenHeight * ; return screenBytes * ;
}
}

  Here is an example of how to instantiate an ImageLoader to use this cache:

 RequestQueue mRequestQueue; // assume this exists.
ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
LruBitmapCache.getCacheSize()));

4.Request JSON

  Volley provides the following classes for JSON requests:

  • JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.
  • JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.

  Both classes are based on the common base class JsonRequest. You use them following the same basic pattern you use for other types of requests. For example, this snippet fetches a JSON feed and displays it as text in the UI:

 TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed"; JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override
public void onResponse(JSONObject response) {
mTxtDisplay.setText("Response: " + response.toString());
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub }
}); // Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);

  For an example of implementing a custom JSON request based on Gson, see the next lesson, Implementing a Custom Request.

 
 
 

Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest的更多相关文章

  1. Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求

    Sending a Simple Request Previous  Next This lesson teaches you to Add the INTERNET Permission Use n ...

  2. Volley HTTP库系列教程(5)自定义一个Volley请求

    Implementing a Custom Request Previous  Next This lesson teaches you to Write a Custom Request parse ...

  3. Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例

    Setting Up a RequestQueue Previous  Next This lesson teaches you to Set Up a Network and Cache Use a ...

  4. Volley HTTP库系列教程(1)简介及优点

    Transmitting Network Data Using Volley Get  started Dependencies and prerequisites Android 1.6 (API ...

  5. SpringBoot 系列教程之事务不生效的几种 case

    SpringBoot 系列教程之事务不生效的几种 case 前面几篇博文介绍了声明式事务@Transactional的使用姿势,只知道正确的使用姿势可能还不够,还得知道什么场景下不生效,避免采坑.本文 ...

  6. 浏览器扩展系列————给MSTHML添加内置脚本对象【包括自定义事件】

    原文:浏览器扩展系列----给MSTHML添加内置脚本对象[包括自定义事件] 使用场合: 在程序中使用WebBrowser或相关的控件如:axWebBrowser等.打开本地的html文件时,可以在h ...

  7. SpringBoot系列教程web篇Servlet 注册的四种姿势

    原文: 191122-SpringBoot系列教程web篇Servlet 注册的四种姿势 前面介绍了 java web 三要素中 filter 的使用指南与常见的易错事项,接下来我们来看一下 Serv ...

  8. 微信内置浏览器私有接口WeixinJSBridge介绍(转)

    这篇文章主要介绍了微信内置浏览器私有接口WeixinJSBridge介绍,本文讲解了发送给好友.分享函数.隐藏工具栏.隐藏三个点按钮等功能,需要的朋友可以参考下 微信网页进入,右上角有三个小点,没错, ...

  9. 微信内置浏览器私有接口WeixinJSBridge介绍

    原文地址:http://www.3lian.com/edu/2015/05-25/216227.html 这篇文章主要介绍了微信内置浏览器私有接口WeixinJSBridge介绍,本文讲解了发送给好友 ...

随机推荐

  1. ASP.NET MVC 4 插件化架构简单实现-思路篇

    用过和做过插件的都会了解插件的好处,园子里也有很多和讨论,但大都只些简单的加载程序集什么的,这里主要讨论的就是使用 ASP.NET MVC 4 来实现每个插件都可以完全从主站点剥离出来,即使只是一个插 ...

  2. 【BZOJ】【1901】【Zju2112】 Dynamic Rankings

    再填个坑. 动态维护区间第K大(带单点修改) 首先裸的区间第K大我们是用的[前缀和]思想,实现O(n)预处理,O(1)找树查询,那么如果是动态的呢?我们可以利用树状数组(BIT)的思想,进行O(log ...

  3. Tomcat漏洞说明与安全加固

    Tomcat是Apache软件基金会的一个免费的.开放源码的WEB应用服务器,可以运行在Linux和Windows等多个平台上,由于其性能稳定.扩展性好.免费等特点深受广大用户的喜爱.目前,互联网上绝 ...

  4. Red hat Linux 安装Node.js 源码安装

    1. 下载源码包 http://nodejs.org/dist/v0.10.29/node-v0.10.29.tar.gz 2.准备安装环境,>python2.6, gcc, g++ pytho ...

  5. wifidog源码分析 - 用户连接过程

    引言 之前的文章已经描述wifidog大概的一个工作流程,这里我们具体说说wifidog是怎么把一个新用户重定向到认证服务器中的,它又是怎么对一个已认证的用户实行放行操作的.我们已经知道wifidog ...

  6. c# 发送消息到Email

    /// <summary>        /// 发送消息到Email        /// </summary>        /// <param name=&quo ...

  7. HDU3507 Print Article(斜率优化dp)

    前几天做多校,知道了这世界上存在dp的优化这样的说法,了解了四边形优化dp,所以今天顺带做一道典型的斜率优化,在百度打斜率优化dp,首先弹出来的就是下面这个网址:http://www.cnblogs. ...

  8. JavaWeb-JDK下载安装

    JDK官方下载地址:http://www.oracle.com/index.html JDK下载: 64位的下64的 JDK安装:(这是32位的) JDK部署测试:(配置环境变量) JAVA_HOME ...

  9. POJ 1496

    #include <iostream> #include <string> using namespace std; int fac(int num); int C(int n ...

  10. C# 中Newtonsoft.Json的安装和使用

    官网参考:http://json.codeplex.com/ 在程序包管理控制台,键入NuGet命令  install-package Newtonsoft.Json  安装Newtonsoft.Js ...