Volley HTTP库系列教程(5)自定义一个Volley请求
Implementing a Custom Request
1.This lesson teaches you to
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 extendingRequest<String>
. See the Volley toolbox classesStringRequest
andImageRequest
for examples of extendingRequest<T>
. - Implement the abstract methods
parseNetworkResponse()
anddeliverResponse()
, 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 aNetworkResponse
, 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请求的更多相关文章
- Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例
Setting Up a RequestQueue Previous Next This lesson teaches you to Set Up a Network and Cache Use a ...
- Volley HTTP库系列教程(1)简介及优点
Transmitting Network Data Using Volley Get started Dependencies and prerequisites Android 1.6 (API ...
- Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求
Sending a Simple Request Previous Next This lesson teaches you to Add the INTERNET Permission Use n ...
- Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest
Making a Standard Request Previous Next This lesson teaches you to Request a String 返回String Requ ...
- Spring 系列教程之自定义标签的解析
Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...
- React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发
React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发 2016/09/23 | React Native技术文章 | Sky丶清| 4 条评论 | 1 ...
- SpringBoot系列教程web篇之Post请求参数解析姿势汇总
作为一个常年提供各种Http接口的后端而言,如何获取请求参数可以说是一项基本技能了,本篇为<190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总>之后的第二篇,对 ...
- SpringBoot系列教程web篇之Get请求参数解析姿势汇总
一般在开发web应用的时候,如果提供http接口,最常见的http请求方式为GET/POST,我们知道这两种请求方式的一个显著区别是GET请求的参数在url中,而post请求可以不在url中:那么一个 ...
- Tomcat系列(6)——Tomcat处理一个HTTP请求的过程
Tomcat的架构图 图三:Tomcat Server处理一个HTTP请求的过程 处理HTTP请求过程 假设来自客户的请求为:http://localhost:8080/test/index.js ...
随机推荐
- 使用HTML5中postMessage实现Ajax中的POST跨域问题
HTML5中提供了在网页文档之间相互接收与发送信息的功能.使用这个功能,只要获取到网页所在窗口对象的实例,不仅仅同源(域+端口号)的web网页之间可以互相通信,甚至可以实现跨域通信. 浏览器支持程度: ...
- hdu 3926 Hand in Hand 同构图
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3926 In order to get rid of Conan, Kaitou KID disguis ...
- BZOJ1500 维修数列
AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=1500 [前言] 据说没打这题就相当于没打过Splay,这题简直就是让你内心崩溃的... 这 ...
- 【CTSC 2015】&【APIO 2015】酱油记
蒟蒻有幸参加了神犇云集的CTSC & APIO 2015,感觉真是被虐成傻逼了……这几天一直没更新博客,今天就来补一下吧~~(不过不是题解……) Day 0 从太原到北京现在坐高铁只需3小时= ...
- Leetcode#61 Rotate List
原题地址 我一直不太理解为什么叫rotate,翻译成"旋转"吧,似乎也不像啊.比如: 1->2->3->4->5->NULL 向右旋转2的距离,变成了 ...
- Build Simple HTTP server
1. The server just support POST&PUT method 2. It is a Python server, and save upload files in sp ...
- 如何优化C语言代码(程序员必读)
1.选择合适的算法和数据结构 应该熟悉算法语言,知道各种算法的优缺点,具体资料请参见相应的参考资料,有很多计算机书籍上都有介绍.将比较慢的顺序查找法用较快的二分查找或乱序查找法代替,插入排序或冒泡排序 ...
- 【Asp.Net WebFrom】分页
Asp.Net WebForm 分页 一. 前言 Asp.Net WebForm 内置的DataPager让人十分蛋疼 本文使用的分页控件是第三方分页控件 AspNetPager,下载地址: 链接: ...
- CamShift算法
拟采用的方法,CamShift算法,即"Continuously Apative Mean-Shift"算法,是一种运动跟踪算法.它主要通过视频图像中运动物体的颜色信息来达到跟踪的 ...
- 李洪强iOS开发之苹果使用预览截图
李洪强iOS开发之苹果使用预览截图 01 在预览的图片中选中你要截得区域 02 - command + C 03 - Command + N 04 - Command + S (保存)