最近Restfull风格比较火,公司很坑,后台外包出去。外包公司扔过来的接口正式restfull风格,一开始看到接口很懵逼。
看懂会用,还是没多大毛病,毛病就出在网络框架不再适合用了。
公司的项目用的是volley作网络框架,正常的访问没啥问题,restfull,就需要注意了。
后台请求时要添加请求头,这个时候只能自己再做相应封装一下:
直接贴代码:
/** * @author: ZengWQ(zwq_em@163.com) * Date: 2017-12-13 * Time: 10:43 * Verssion: 1.0 * Describe: */ public class CommonRequst extends StringRequest { public CommonRequst(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); } public CommonRequst(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(url, listener, errorListener); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String ,String>headers=super.getHeaders(); if (headers==null|headers.equals(Collections.<String, String>emptyMap())){ headers=new HashMap<String, String>(); } headers.put("XXX","xxx");//添加请求头 return headers; } }
然而:
这么处理只能解决正常http协议中的状态码:
后台自定义的状态码时,volley框架就不行了:贴下异常
java.net.ProtocolException: Unexpected status line: HTTP/1.0 1012 UNKNOWN
正常情况 响应头的信息是: HTTP/1.0 200 ok
而这个1012 是restfull风格中自己定义的响应码,这个时候标准的volley框架就解析不到1012 是什么意思,直接抛异常;
因为需求着急,自己动手丰衣足食,自己撸了一段代码去适配这个restfull风格。
上代码:
/** * @author: ZengWQ(zwq_em@163.com) * Date: 2017-12-18 * Time: 15:30 * Verssion: 1.0 * Describe: 该http是封装给restfull风格用