Android Network Architecture-OkHttp + Volley + Gson, okhttpgson

Source: Internet
Author: User

Android Network Architecture-OkHttp + Volley + Gson, okhttpgson

Previously, HttpClient was encapsulated by itself. However, Volley is used for mainstream network requests, and OkHttp is also very popular.

These frameworks are not introduced. This article uses Volley to process Http requests in combination with OkHttp, and uses Gson custom requests to implement Android network functions.

Prepare the jar package:

, Ignoring the universal-image-loader, too lazy to delete it

 

RequestQueue only needs one, so we put it in StaticVariable.

import com.android.volley.RequestQueue;import com.liujing.csoc.utils.HttpUtils;public class StaticVariable {    private static RequestQueue mRequestQueue;    public static void clear() {        HttpUtils.cancelAllRequest();        mRequestQueue = null;    }    public static RequestQueue getRequestQueue() {        return mRequestQueue;    }    public static void setRequestQueue(RequestQueue paramRequestQueue) {        mRequestQueue = paramRequestQueue;    }}
Import java. io. IOException; import java.net. httpURLConnection; import java.net. URL; import android. text. textUtils; import com. android. volley. request; import com. android. volley. requestQueue; import com. android. volley. toolbox. hurlStack; import com. android. volley. toolbox. volley; import com. squareup. okhttp. okHttpClient; import com. squareup. okhttp. okUrlFactory; import com. liujing. csoc. application. topSecCsocApplic Ation; import com. liujing. csoc. iconstant. staticVariable; public class HttpUtils {/*** Add a Request to the queue because OkHttp is used as the transport layer of Volley, therefore, an HttpStack parameter * @ param request */public static void addRequest (Request <?> is added. Request) {if (request! = Null) {if (StaticVariable. getRequestQueue () = null) {StaticVariable. setRequestQueue (Volley. newRequestQueue (TopSecCsocApplication. getContext ();} Volley. newRequestQueue (TopSecCsocApplication. getContext (), new OkHttpStack (); StaticVariable. getRequestQueue (). add (request) ;}}/*** cancel all requests */public static void cancelAllRequest () {RequestQueue localRequestQueue = StaticVariable. getReques TQueue (); if (localRequestQueue! = Null) {localRequestQueue. cancelAll (new RequestQueue. RequestFilter () {@ Override public boolean apply (Request <?> Request) {return true ;}}); localRequestQueue. stop () ;}}/*** cancel the specified Request * @ param tag */public static void cancelRequestByTag (String tag) {if (! TextUtils. isEmpty (tag) {if (StaticVariable. getRequestQueue ()! = Null) {StaticVariable. getRequestQueue (). cancelAll (tag) ;}}/ *** defines OkHttpStack * @ author Administrator **/private static class OkHttpStack extends HurlStack {private final OkUrlFactory okUrlFactory; public OkHttpStack () {this (new OkUrlFactory (new OkHttpClient ();} public OkHttpStack (OkUrlFactory okUrlFactory) {if (okUrlFactory = null) {throw new NullPointerException ("Client must not be null. ");} this. okUrlFactory = okUrlFactory;} @ Override protected HttpURLConnection createConnection (URL url) throws IOException {return okUrlFactory. open (url );}}}

 

Custom Request with Gson

Import java. io. unsupportedEncodingException; import java. lang. reflect. type; import java. util. iterator; 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. liste Ner; import com. android. volley. toolbox. httpHeaderParser; import com. google. gson. gson; /*** Volley custom Request * @ author liujing * @ param <T> */public class CsocRequest <T> extends Request <T> {public static final int GET = Method. GET; public static final int POST = Method. POST; private static Gson gson = new Gson (); private Type mType; private final ResponeListener <T> mlistener; private Map <String, Str Ing> mParams; // custom callback for convenient use of public interface ResponeListener <T> extends ErrorListener, listener <T >{}/*** by default, the http request is submitted in get mode * @ param url * @ param type * @ param params * @ param listener */public CsocRequest (String url, type type, Map <String, String> params, ResponeListener <T> listener) {super (GET, getUrl (url, params), listener); this. mlistener = listener; this. mType = type; setShouldCache (false ); }/*** Added the method parameter to select get or post to submit an http request * @ param method * @ param url * @ param type * @ param params * @ param listener */public CsocRequest (int method, string url, Type type, Map <String, String> params, ResponeListener <T> listener) {super (method, method = POST? Url: getUrl (url, params), listener); this. mlistener = listener; this. mType = type; if (method = POST) {mParams = params;} setShouldCache (false) ;}@ Override protected Map <String, String> getParams () throws AuthFailureError {if (mParams! = Null) {return mParams;} else {return super. getParams () ;}}// construct a url. For get requests, you can also directly transmit the private static String getUrl (String url, Map <String, String> params) {if (params! = Null) {Iterator <String> it = params. keySet (). iterator (); StringBuffer sb = null; while (it. hasNext () {String key = it. next (); String value = params. get (key); if (sb = null) {sb = new StringBuffer (); sb. append ("? ");} Else {sb. append ("&");} sb. append (key); sb. append ("="); sb. append (value);} url + = sb. toString () ;}return url ;}@ Override protected Response <T> parseNetworkResponse (NetworkResponse response) {try {T result; String jsonStr = new String (response. data, HttpHeaderParser. parseCharset (response. headers); result = gson. fromJson (jsonStr, mType); return Response. success (result, HttpHeaderParser. parseCacheHeaders (response);} catch (UnsupportedEncodingException e) {e. printStackTrace (); return Response. error (new ParseError (e) ;}@ Override protected void deliverResponse (T response) {mlistener. onResponse (response );}}

 

Let's see how to use it. It's actually a new Request and then added to the queue through HttpUtils.

Request Parameters of Params get or post

The url is the url.

Type Gson parses json according to Type

private void loadData(int pageNUM, String loadDate) {        Map<String, String> Params = new HashMap<String, String>();        Params.put("cusId", customerId);        Params.put("session_id", mSession_id);        Params.put("pageNo", String.valueOf(pageNUM));        Params.put("pageSize", String.valueOf(IConstant.PAGE_LOAD_NUM));        Params.put("date", loadDate);        String url = IConfig.URL + IConfig.CONTENT_MONITOR;        Type type = new TypeToken<ResultData<ContentMonitorBean<ContentMonitorDataBean>>>() {
     }.getType(); CsocRequest<ResultData<BaseBean>> cr = new CsocRequest<ResultData<BaseBean>>( url, type, Params, this); HttpUtils.addRequest(cr); }

 

Receive request results and refresh the page

Implement the previously defined ResponeListener. onErrorResponse and onResponse indicate request failure and success.

Public class BaseFragment extends Fragment implements ResponeListener <ResultData <BaseBean >{@ Override public void onErrorResponse (VolleyError error) {dismissNetDialog (); Toast. makeText (mActivity, "loading failed", Toast. LENGTH_SHORT ). show () ;}; @ Override public void onResponse (ResultData <BaseBean> response) {dismissNetDialog (); if (response! = Null) {// update data, refresh the interface ....}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.