• Android网络开发之Volley--Volley自定义Request


    1、自定义一个解析Json的Request,这里使用JackSon框架来解析Json。你也可以自定义一个解析XML的Request,或者使用FastSon来解析Json。

    2、我们首先来看一下StringRequest的源码。继承自Request<T>,主要是重写parseNetworkResponse()和deliverResponse()方法。

    public class StringRequest extends Request<String> {
        private final Listener<String> mListener;
    
        /**
         * Creates a new request with the given method.
         *
         * @param method the request {@link Method} to use
         * @param url URL to fetch the string at
         * @param listener Listener to receive the String response
         * @param errorListener Error listener, or null to ignore errors
         */
        public StringRequest(int method, String url, Listener<String> listener,
                ErrorListener errorListener) {
            super(method, url, errorListener);
            mListener = listener;
        }
    
        /**
         * Creates a new GET request.
         *
         * @param url URL to fetch the string at
         * @param listener Listener to receive the String response
         * @param errorListener Error listener, or null to ignore errors
         */
        public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
            this(Method.GET, url, listener, errorListener);
        }
    
        @Override
        protected void deliverResponse(String response) {
            mListener.onResponse(response);
        }
    
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String parsed;
            try {
                parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            } catch (UnsupportedEncodingException e) {
                parsed = new String(response.data);
            }
            return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
        }
    }

    3、首先定义实体类

    public class Weather {
        private WeatherInfo weatherinfo;
    
        public WeatherInfo getWeatherinfo() {
            return weatherinfo;
        }
    
        @JsonProperty("weatherinfo")
        public void setWeatherinfo(WeatherInfo weatherinfo) {
            this.weatherinfo = weatherinfo;
        }
    
    }
    public class WeatherInfo {
        private String city;
        private String cityid;
        private String temp;
        private String WD;
        private String WS;
        private String SD;
        private String WSE;
        private String time;
        private String isRadar;
        private String Radar;
        private String njd;
        private String qy;
    
        public String getCity() {
            return city;
        }
    
        @JsonProperty("city")
        public void setCity(String city) {
            this.city = city;
        }
    
        public String getCityid() {
            return cityid;
        }
    
        @JsonProperty("cityid")
        public void setCityid(String cityid) {
            this.cityid = cityid;
        }
    
        public String getTemp() {
            return temp;
        }
    
        @JsonProperty("temp")
        public void setTemp(String temp) {
            this.temp = temp;
        }
    
        public String getWD() {
            return WD;
        }
    
        @JsonProperty("WD")
        public void setWD(String wD) {
            WD = wD;
        }
    
        public String getWS() {
            return WS;
        }
    
        @JsonProperty("WS")
        public void setWS(String wS) {
            WS = wS;
        }
    
        public String getSD() {
            return SD;
        }
    
        @JsonProperty("SD")
        public void setSD(String sD) {
            SD = sD;
        }
    
        public String getWSE() {
            return WSE;
        }
    
        @JsonProperty("WSE")
        public void setWSE(String wSE) {
            WSE = wSE;
        }
    
        public String getTime() {
            return time;
        }
    
        @JsonProperty("time")
        public void setTime(String time) {
            this.time = time;
        }
    
        public String getIsRadar() {
            return isRadar;
        }
    
        @JsonProperty("isRadar")
        public void setIsRadar(String isRadar) {
            this.isRadar = isRadar;
        }
    
        public String getRadar() {
            return Radar;
        }
    
        @JsonProperty("Radar")
        public void setRadar(String radar) {
            Radar = radar;
        }
    
        public String getNjd() {
            return njd;
        }
    
        @JsonProperty("njd")
        public void setNjd(String njd) {
            this.njd = njd;
        }
    
        public String getQy() {
            return qy;
        }
    
        @JsonProperty("qy")
        public void setQy(String qy) {
            this.qy = qy;
        }
    
    }

    4、实现JacksonRequest

    public class JacksonRequest<T> extends Request<T>{
        private final Listener<T> mListener;
        
        private Class<T> mClass;
        
        private static ObjectMapper objectMapper = new ObjectMapper();
    
        public JacksonRequest(int method, String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) {
            super(method, url, errorListener);
            // TODO Auto-generated constructor stub
            mListener = listener;
            mClass = clazz;
        }
        
        public JacksonRequest(String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener){
            this(Method.GET, url, clazz, listener, errorListener);
        }
    
        @Override
        protected Response<T> parseNetworkResponse(NetworkResponse response) {
            // TODO Auto-generated method stub
            try {
                String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                return Response.success(objectMapper.readValue(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                return Response.error(new ParseError(e));
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        protected void deliverResponse(T response) {
            // TODO Auto-generated method stub
            mListener.onResponse(response);
        }
    
    }

    5、Jackson的使用,和StringRequest的使用是一样的。

    public class JacksonActivity extends Activity {
        private RequestQueue requestQueue;
        
        private TextView mTvShow;
        
        private String result = "";
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_jackson);
            
            initView();
        }
        
        public void initView(){
            mTvShow = (TextView) findViewById(R.id.tv_jackson);
            
            requestQueue = Volley.newRequestQueue(getBaseContext());
            requestQueue.add(jacksonRequest);
            requestQueue.start();
        }
        
        private JacksonRequest<Weather> jacksonRequest = new JacksonRequest<Weather>("http://www.weather.com.cn/data/sk/101010100.html", 
                Weather.class,
                new Response.Listener<Weather>() {
    
                    @Override
                    public void onResponse(Weather response) {
                        // TODO Auto-generated method stub
                        WeatherInfo info = response.getWeatherinfo();
                        result += info.getCity() + "
    " + info.getTemp() + "
    " +info.getTime();
                        mTvShow.setText(result);
                    }
                }, new Response.ErrorListener(){
    
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        mTvShow.setText(error.toString());
                    }
                    
                });
    }

    6、不要忘记加入网络访问权限

    <uses-permission android:name="android.permission.INTERNET"/>

    7、参考博文:

    http://blog.csdn.net/guolin_blog/article/details/17482095/

  • 相关阅读:
    POJ 2029 (二维树状数组)题解
    HDU 4819 Mosaic (二维线段树&区间最值)题解
    HDU 1823 Luck and Love (二维线段树&区间最值)题解
    POJ1061 青蛙的约会(扩展欧几里得)题解
    POJ 2155 Matrix (二维树状数组)题解
    POJ 1751 Highways(最小生成树&Prim)题解
    HDU 6148 Valley Numer (数位DP)题解
    HDU3652 B-number(数位DP)题解
    HDU 4734 (数位DP)题解
    HDU 2089 不要62 (数位DP)题解
  • 原文地址:https://www.cnblogs.com/begin1949/p/4925634.html
Copyright © 2020-2023  润新知