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. C#_音乐播放器_用ListBox显示歌词

    在用ListBox显示歌词的时候,可以显示多行,同时可以控制每一行显示的样式等等.控制显示样式是在它的DrawItem事件中来控制的.首先要先将ListBox的DrawMode属性设置为OwnerDr ...

  2. poj 1273 Drainage Ditches 最大流入门题

    题目链接:http://poj.org/problem?id=1273 Every time it rains on Farmer John's fields, a pond forms over B ...

  3. 【BZOJ】【2301】problem b

    莫比乌斯反演/容斥原理 Orz PoPoQQQ PoPoQQQ莫比乌斯函数讲义第一题. for(i=1;i<=n;i=last+1){ last=min(n/(n/i),m/(m/i)); …… ...

  4. Linux VPS 免费管理面板推荐

    现在各种国内外VPS,云主机横行,越来越多的站长接受在VPS上建站,很多VPS主机售价便宜,性能优秀,但都是基于linux系统的,如openvz的主机,linux服务器系统主要是通过shell命令行来 ...

  5. StoreKit framework

    关于In-APP Purchase 1. 中文文档 基本流程: http://www.cnblogs.com/wudan7/p/3621763.html 三种购买形式及StoreKit code介绍: ...

  6. JavaScript之Throw、Try 、Catch讲解

    try 语句测试代码块的错误. catch 语句处理错误. throw 语句创建自定义错误. 错误一定会发生 当 JavaScript 引擎执行 JavaScript 代码时,会发生各种错误: 可能是 ...

  7. js生成唯一值的函数

    利用了js的闭包性质 var uniqueNumber = (( function(){ var value = 0; return function(){ return ++value; }; }) ...

  8. Sqli-labs less 21

    Less-21 本关对cookie进行了base64的处理,其他的处理流程和less20是一样的. 我们这里可以利用less20同样的方法,但是需要将payload进行base64编码处理(注意这里对 ...

  9. Sqli-labs less 64

    Less-64 此处的sql语句为 $sql="SELECT * FROM security.users WHERE id=(($id)) LIMIT 0,1"; 示例payloa ...

  10. 【译】 沙箱中的间谍 - 可行的 JavaScript 高速缓存区攻击

    王龑 - MAY 27, 2015 原文连接 The Spy in the Sandbox – Practical Cache Attacks in Javascript 相关论文可在 https:/ ...