Android网络开发之Volley--Volley自定义Request
生活随笔
收集整理的這篇文章主要介紹了
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);}@Overrideprotected void deliverResponse(String response) {mListener.onResponse(response);}@Overrideprotected 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 stubmListener = listener;mClass = clazz;}public JacksonRequest(String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener){this(Method.GET, url, clazz, listener, errorListener);}@Overrideprotected Response<T> parseNetworkResponse(NetworkResponse response) {// TODO Auto-generated method stubtry {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 blockreturn 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;}@Overrideprotected 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 = "";@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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>() {@Overridepublic void onResponse(Weather response) {// TODO Auto-generated method stubWeatherInfo info = response.getWeatherinfo();result += info.getCity() + "\n" + info.getTemp() + "\n" +info.getTime();mTvShow.setText(result);}}, new Response.ErrorListener(){@Overridepublic 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/
轉載于:https://www.cnblogs.com/begin1949/p/4925634.html
總結
以上是生活随笔為你收集整理的Android网络开发之Volley--Volley自定义Request的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MATLAB 人脸定位
- 下一篇: 学了近一个月的java web 感想