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 学习笔记--10---基本包装类型

    练习中使用的浏览器是IE10,如果有什么错误或者不同意见,希望各位朋友能够指正,练习代码附在后面 1.基本包装类型:    首先是基本类型,但又是特殊的引用类型,因为他们可以调用系统的方法,这种类型就 ...

  2. Basic knowledge of html (keep for myself)

    1. 通常标签 <strong> 替换加粗标签 <b> 来使用, <em> 替换 <i>标签使用. 2. 在 <head>元素中你可以插入脚 ...

  3. VC++之GetLastError()使用说明

    VC中GetLastError()获取错误信息的使用 在VC中编写应用程序时,经常需要涉及到错误处理问题.许多函数调用只用TRUE和FALSE来表明函数的运行结果.一旦出现错误,MSDN中往往会指出请 ...

  4. 在 Java 中如何更高效地存储和管理 SQL 语句?

    [编者按]还在为管理 Java 代码中的 SQL 语句而烦恼吗?让 Zemian 帮你摆脱困境吧!本文系 OneAPM 工程师编译整理 注意:使用java.util.Properties#loadFr ...

  5. 未能正确加载“Microsoft.VisualStudio.Editor.Implementation.EditorPackage”

    VS2012启动/加载项目出问题 未能正确加载“Microsoft.VisualStudio.Editor.Implementation.EditorPackage, Microsoft.Visual ...

  6. UVA 10943 How do you add? DP

    Larry is very bad at math — he usually uses a calculator, whichworked well throughout college. Unfor ...

  7. Node.js缓冲模块Buffer

    前言 Javascript是为浏览器而设计的,能很好的处理unicode编码的字符串,但对于二进制或非unicode编码的数据就显得无能为力. Node.js继承Javascript的语言特性,同时又 ...

  8. Lines演示程序

    #include "stdafx.h"#include "d3d9.h"#include "d3dx9.h" #pragma comment ...

  9. 李洪强iOS经典面试题12

     1.说说响应链 答: 事件响应链.包括点击事件,画面刷新事件等.在视图栈内从上至下,或者从下之上传播. 可以说点事件的分发,传递以及处理.具体可以去看下touch事件这块.因为问的太抽象化了 严重怀 ...

  10. Dice chrone execise

    def score(dices_input): count = {}.fromkeys(range(1, 7), 0) points = 0 for dice_side in dices_input: ...