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. js中常用数组方法concat join push pop slice splice shift

    javascript给我们很多常用的 数组方法,极大方便了我们做程序.下面我们来介绍下常用的集中数组方法. 比如 concat() join() push() pop() unshift() shif ...

  2. geotools解析SLD中的elsefilter为什么里面的filter无效

    原因是在org.geotools.renderer.lite.StreamingRenderer中的process函数: /** * @param rf * @param feature * @par ...

  3. 深入理解asp.net SessionState

    web Form 网页是基于HTTP的,它们没有状态, 这意味着它们不知道所有的请求是否来自同一台客户端计算机,网页是受到了破坏,以及是否得到了刷新,这样就可能造成信息的丢失. 于是, 状态管理就成了 ...

  4. Sqli-labs less 19

    Less-19 从源代码中我们可以看到我们获取到的是HTTP_REFERER 那和less18是基本一致的,我们从referer进行修改. 还是像less18一样,我们只给出一个示例 将referer ...

  5. Solr笔记--转载

    Solr 是一种可供企业使用的.基于 Lucene 的搜索服务器,它支持层面搜索.命中醒目显示和多种输出格式.在这篇分两部分的文章中,Lucene Java™ 的提交人 Grant Ingersoll ...

  6. cf div2 238 D

    D. Toy Sum time limit per test 1 second memory limit per test 256 megabytes input standard input out ...

  7. 2014多校第十场1004 || HDU 4974 A simple water problem

    题目链接 题意 : n支队伍,每场两个队伍表演,有可能两个队伍都得一分,也可能其中一个队伍一分,也可能都是0分,每个队伍将参加的场次得到的分数加起来,给你每个队伍最终得分,让你计算至少表演了几场. 思 ...

  8. UVA 10892 LCM Cardinality 数学

    A pair of numbers has a unique LCM but a single number can be the LCM of more than one possiblepairs ...

  9. BZOJ 1008: [HNOI2008]越狱 快速幂

    1008: [HNOI2008]越狱 Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生 ...

  10. 15.RDD 创建内幕解析

    第15课:RDD创建内幕 RDD的创建方式 Spark应用程序运行过程中,第一个RDD代表了Spark应用程序输入数据的来源,之后通过Trasformation来对RDD进行各种算子的转换,来实现具体 ...