Implementing a Custom Request

Previous  Next

2.Write a Custom Request

  Most requests have ready-to-use implementations in the toolbox; if your response is a string, image, or JSON, you probably won't need to implement a custom Request.

For cases where you do need to implement a custom request, this is all you need to do:

  • Extend the Request<T> class, where <T> represents the type of parsed response the request expects. So if your parsed response is a string, for example, create your custom request by extending Request<String>. See the Volley toolbox classes StringRequest and ImageRequest for examples of extending Request<T>.
  • Implement the abstract methods parseNetworkResponse() and deliverResponse(), described in more detail below.

2.1 parseNetworkResponse

  A Response encapsulates a parsed response for delivery, for a given type (such as string, image, or JSON). Here is a sample implementation of parseNetworkResponse():

 @Override
protected Response<T> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
   return Response.success(gson.fromJson(json, clazz),
              HttpHeaderParser.parseCacheHeaders(response));
}
// handle errors
  //...
}

  Note the following:

  • parseNetworkResponse() takes as its parameter a NetworkResponse, which contains the response payload as a byte[], HTTP status code, and response headers.
  • Your implementation must return a Response<T>, which contains your typed response object and cache metadata or an error, such as in the case of a parse failure.

  If your protocol has non-standard cache semantics, you can build a Cache.Entry yourself, but most requests are fine with something like this:

return Response.success(myDecodedObject,
HttpHeaderParser.parseCacheHeaders(response));

  Volley calls parseNetworkResponse() from a worker thread. This ensures that expensive parsing operations, such as decoding a JPEG into a Bitmap, don't block the UI thread.

2.2 deliverResponse

  Volley calls you back on the main thread with the object you returned in parseNetworkResponse(). Most requests invoke a callback interface here, for example:

protected void deliverResponse(T response) {
listener.onResponse(response);

2.3 Example: GsonRequest

  Gson is a library for converting Java objects to and from JSON using reflection. You can define Java objects that have the same names as their corresponding JSON keys, pass Gson the class object, and Gson will fill in the fields for you. Here's a complete implementation of a Volley request that uses Gson for parsing:

 import java.io.UnsupportedEncodingException;
import java.util.Map; import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException; public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener; /**
* Make a GET request and return a parsed object from JSON.
*
* @param url URL of the request to make
* @param clazz Relevant class object, for Gson's reflection
* @param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Listener<T> listener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
} @Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
} @Override
protected void deliverResponse(T response) {
listener.onResponse(response);
} @Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
return Response.success(gson.fromJson(json, clazz),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}

  使用代码

   /*
* 自定义一个request
*/
public void onClickCustomRequest(View btn){
String url = "http://192.168.1.100/gsonrequest.php";//返回json数据
//1,得到一个RequestQueue
RequestQueue queue = Volley.newRequestQueue(this);
//2,构造一个自定义请求,返回Person,Person是自定义的类
//3,构造请求的header
Map<String,String> headers = new HashMap<String, String>();
headers.put("XXX", "XXX");
headers.put("XXX", "XXX"); //4,构造自定义的请求
GsonRequest<Person> jsonRequest = new GsonRequest<Person>(url, Person.class, headers
, new Response.Listener<Person>() {
@Override
public void onResponse(Person person) {
output.append("onResponse");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError paramVolleyError) {
output.append(paramVolleyError.getMessage());
}
});
//5,将请求加到请求队列中.
queue.add(jsonRequest);
}

  Volley provides ready-to-use JsonArrayRequest and JsonArrayObject classes if you prefer to take that approach. See Using Standard Request Types for more information.

Volley HTTP库系列教程(5)自定义一个Volley请求的更多相关文章

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

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

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

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

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

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

  4. Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest

    Making a Standard Request Previous  Next   This lesson teaches you to Request a String 返回String Requ ...

  5. Spring 系列教程之自定义标签的解析

    Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...

  6. React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发

    React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发   2016/09/23 |  React Native技术文章 |  Sky丶清|  4 条评论 |  1 ...

  7. SpringBoot系列教程web篇之Post请求参数解析姿势汇总

    作为一个常年提供各种Http接口的后端而言,如何获取请求参数可以说是一项基本技能了,本篇为<190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总>之后的第二篇,对 ...

  8. SpringBoot系列教程web篇之Get请求参数解析姿势汇总

    一般在开发web应用的时候,如果提供http接口,最常见的http请求方式为GET/POST,我们知道这两种请求方式的一个显著区别是GET请求的参数在url中,而post请求可以不在url中:那么一个 ...

  9. Tomcat系列(6)——Tomcat处理一个HTTP请求的过程

    Tomcat的架构图   图三:Tomcat Server处理一个HTTP请求的过程 处理HTTP请求过程 假设来自客户的请求为:http://localhost:8080/test/index.js ...

随机推荐

  1. Poj2420 A Star not a Tree? 模拟退火算法

    题目链接:http://poj.org/problem?id=2420 题目大意:每组数据中给n个点(n<=100),求平面中一个点使得这个点到n个点的距离之和最小. 分析:一开始看到这个题想必 ...

  2. Oracle 11g安装与使用

    作为一个新手,学习Oracle,就连安装oracle都感觉到吃力! 经过不间断的搜罗.学习.尝试,找到一些比较有用的“指导”,罗列如下: 1. http://www.2cto.com/database ...

  3. Leetcode#61 Rotate List

    原题地址 我一直不太理解为什么叫rotate,翻译成"旋转"吧,似乎也不像啊.比如: 1->2->3->4->5->NULL 向右旋转2的距离,变成了 ...

  4. QGraphics

    QGraphicsView和QGraphicsScene QGraphicsScene提供一个场景,可以添加各种item,QGraphicsView用于将元素显示,并支持旋转和缩放:可以将QGraph ...

  5. 如何将控制台程序包装成windows服务

    1. 新建一个项目,或者从选择当前解决方案--右键-添加--新建项目 2. 选择(项目类型)Visual C#项目,(模板)Windows 服务,填写要创建的服务名称(修改默认的WindowServi ...

  6. c#比较器 排序

    原地址:http://blog.csdn.net/xutao_ustc/article/details/6314057 class Program { static void Main(string[ ...

  7. Sqli-labs less 31

    Less-31 Less-31与上述两个例子的方式是一样的,我们直接看到less-31的sql语句: 所以payload为: http://127.0.0.1:8080/sqli-labs/Less- ...

  8. linux下命令行查看Memcached运行状态(shell)

    stats查看memcached状态的基本命令,通过这个命令可以看到如下信息:STAT pid 22459                             进程IDSTAT uptime 10 ...

  9. 微信公众号token的asp.net脚本

    老板让我搞一个微信公众号.好吧.前面都很EZ,直到要使用一个token验证服务器的有效性. 看了下文档,大概意思就是微信的服务器用GET请求访问你的服务器. 其中包含了signature,nonce, ...

  10. 如何开发一个自己的 RubyGem?

    「如何测试你的 RubyGem?」的前导文章 什么是 RubyGem RubyGem 是 Ruby 语言的标准源码打包格式. 大家一直都在用gem这个命令,但是很少有人知道这个东西是怎么来的,这里我从 ...