How to implement a network request module that is easier to use, more common, easier to modify, and less crash, crash Module

Source: Internet
Author: User

How to implement a network request module that is easier to use, more common, easier to modify, and less crash, crash Module

Keywords: Observer mode, encapsulation, unified interface
 
Use the jar package okhttp and fastjson
 
Package com. example. sax; import com. example. sax. httpRequest. onHttpResponseListener; import android. app. activity; import android. OS. bundle; import android. widget. toast;/*** is there a lot of clarity in the Activity, all repeated operations are handed over to HttpRequest for processing * @ author Administrator **/public class TestActivity extends Activity implements OnHttpResponseListener {/*** to distinguish requests with requestCode, if you use an anonymous internal class, you do not need requestCode */private final int LOGIN_CODE = 1; private final int INFO_CODE = 2;/*** request success status code, as specified by the server */private int REQUEST_SUCCESS = 1; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); HttpRequest. getInstance (). login ("zhang", "123456", LOGIN_CODE, this); HttpRequest. getInstance (). getInfo (INFO_CODE, this); // you can also use an anonymous internal class. At this time, requestCode is useless. // HttpRequest. getInstance (). getInfo (0, new OnHttpResponseListener () {// @ Override // public void onHttpRequestSuccess (int requestCode, int serverResultCode, // String json) {// TODO Auto-generated method stub //} // @ Override // public void onHttpRequestError (int requestCode, Exception exception) {// TODO Auto-generated method stub //});} @ Overridepublic void onHttpRequestSuccess (int requestCode, int serverResultCode, String json) {// you do not need to determine whether the request is empty or try {} catch {}. After the request ends in HttpRequest, try {} catch {} has passed the switch (requestCode) {case LOGIN_CODE: if (serverResultCode = REQUEST_SUCCESS) {// resolution exceptions may occur even if serverResultCode = REQUEST_SUCCESS json. You can encapsulate fastjson and return null if parsing fails, in this way, you do not need to be empty or try {} catch {}. LoginDO loginDO = Json. parseObject (json, LoginDO. class); // parse json, Toast in one sentence. makeText (getApplicationContext (), "request successful" + loginDO. getName () + "" + loginDO. getToken (), 1 ). show ();} else {Toast. makeText (getApplicationContext (), "Logon Failed", 1 ). show ();} break; case INFO_CODE: if (serverResultCode = REQUEST_SUCCESS) {} else {} break ;}@overridepublic void onHttpRequestError (int requestCode, Exception exception) {// you do not need to determine whether the request is empty or try {} catch {}. After the request ends in HttpRequest, try {} catch {} has passed the switch (requestCode) {case LOGIN_CODE: Toast. makeText (getApplicationContext (), "Logon Failed" + exception, 1 ). show (); break; case INFO_CODE: Toast. makeText (getApplicationContext (), "failed to get" + exception, 1 ). show (); break ;}}}
 
 
 





Package com. example. sax; import java. util. arrayList; import java. util. list; import java. util. concurrent. timeUnit; import org. json. JSONObject; import android. OS. asyncTask; import com. squareup. okhttp. formEncodingBuilder; import com. squareup. okhttp. okHttpClient; import com. squareup. okhttp. request; import com. squareup. okhttp. requestBody; import com. squareup. okhttp. response;/*** when you need to add a new network request, you only need to define a method in the class and then call the http Post or httpGet <br/> * allow all network requests to pass httpPost or httpGet. It will be easier to modify it later, whether it is replaced with volley or other network request jar packages, you only need to modify an httpPost or httpGet file. * <br/> *. If the same processing is required for each network request to end, you only need to process it in the two methods. ** @ author Young **/public class HttpRequest {private static HttpRequest instance; /*** Singleton * @ return */public static synchronized HttpRequest getInstance () {if (instance = null) {instance = new HttpRequest ();} return instance ;}/ * ** Log on to the <br/> * Activity and call this method. <br/> ** @ param account * @ param pwd * @ param requestCode * @ param listener */public void login (String account, string pwd, int requestCode, OnHttpResponseListener listener) {List <Parameter> list = new ArrayList <> (); // The form of the Request Parameter key-value pair. The key can be listed by the server. add (new Parameter ("account", account); list. add (new Parameter ("password", pwd); // The second Parameter is urlhttpPost (null, "http://xxx.xxx.xxx/logi N ", requestCode, listener);}/*** get information through the get request * @ param requestCode * @ param listener */public void getInfo (int requestCode, OnHttpResponseListener listener) {// The second Parameter is urlhttpGet (new ArrayList <Parameter> (), "http://xxx.xxx.xxx/info", requestCode, listener);}/***** @ param paramList request Parameter list, (One key can correspond to multiple values) * @ param url interface url * @ param requestCode Request Code, similar to the Request Code in onActivityResult. When the same activity implements the interface <br/>, * multiple Initiators Network requests, all requests will be called back after the request ends <br/> * {@ link OnHttpResponseListener # onHttpRequestError (int, Exception )} <br/> * or <br/> * {@ link OnHttpResponseListener # onHttpRequestSuccess (int, int, String )} <br/> * in an activity, requestCode can be used to differentiate requests. serverResultCode is the status code returned by the server, and json is the data json. <br/> * (note: all data returned by the server must be in the following format: {"result": 1, "data": "json or json "}) ** @ param listener */private void httpPost (final List <Parameter> para MList, final String url, final int requestCode, final OnHttpResponseListener listener) {new AsyncTask <Void, Void, Exception> () {String datajson; int code; @ Overrideprotected Exception doInBackground (Void... params) {try {OkHttpClient client = new OkHttpClient (); // timeout client. setConnectTimeout (10, TimeUnit. SECONDS); client. setWriteTimeout (10, TimeUnit. SECONDS); client. setReadTimeout (10, TimeUnit. SECO NDS); FormEncodingBuilder fBuilder = new FormEncodingBuilder (); for (Parameter p: paramList) {fBuilder. add (p. key, p. value);} RequestBody body = fBuilder. build (); Request request = new Request. builder (). url (url ). post (body ). build (); Response response = client.newcall(requestcmd.exe cute (); if (! Response. isSuccessful () {return new Exception ("Unexpected code" + response. code ();} else {String json = response. body (). string (); // get the server data JSONObject jsonObject = new JSONObject (json); code = jsonObject. getInt ("result"); datajson = jsonObject. getString ("data"); return null ;}catch (Exception e1) {return e1 ;}@ Overrideprotected void onPostExecute (Exception exception Exception) {super. onPostExecute (exception); Try {// here use try {} catch {} to catch all exceptions. When the onHttpRequestSuccess callback in the Activity encounters various exceptions, such as json parsing exceptions or null pointers, all exceptions can be caught here, instead, you do not have to judge the null if (exception = null) {if (listener! = Null) listener. onHttpRequestSuccess (requestCode, code, datajson);} else {if (listener! = Null) listener. onHttpRequestError (code, exception) ;}} catch (Throwable e) {e. printStackTrace () ;}}cmd.exe cute () ;}/ ***** @ param paramList: List of request parameters (one key can correspond to multiple values) * @ param url interface url * @ param requestCode Request Code, similar to the Request Code in onActivityResult. When multiple network requests are initiated in the same activity <br/>, all requests are called back after the request ends. <br/> * {@ link OnHttpResponseListener # onHttpRequestError (int, Exception)} <br/> * or <br/> * {@ link OnHttpResponseListener # onHttp RequestSuccess (int, int, String)} <br/> * in the activity, requestCode can be used to differentiate requests. serverResultCode is the status code returned by the server, json is the data json <br/> * (Note: All data formats returned by the server are as follows: {"result": 1, "data ": "Either json or json"}) ** @ param listener */private void httpGet (final List <Parameter> paramList, final String url, final int requestCode, final OnHttpResponseListener listener) {new AsyncTask <Void, Void, Exception> () {String datajson; Int code; @ Overrideprotected Exception doInBackground (Void... params) {try {OkHttpClient client = new OkHttpClient (); client. setConnectTimeout (10, TimeUnit. SECONDS); client. setWriteTimeout (10, TimeUnit. SECONDS); client. setReadTimeout (10, TimeUnit. SECONDS); // concatenate urlStringBuffer sb = new StringBuffer (); sb. append (url); sb. append ("? "); Parameter p = paramList. get (0); sb. append (p. key); sb. append ("="); sb. append (p. value); for (int I = 1; I <paramList. size (); I ++) {Parameter parameter = paramList. get (I); sb. append ("&"); sb. append (parameter. key); sb. append ("="); sb. append (parameter. value);} Request request = new Request. builder (). url (sb. toString ()). build (); final Response response = client.newcall(requestcmd.exe cute (); if (! Response. isSuccessful () {return new Exception ("Unexpected code" + response. code ();} else {String json = response. body (). string (); // get the server data JSONObject jsonObject = new JSONObject (json); code = jsonObject. getInt ("result"); datajson = jsonObject. getString ("data"); return null ;}catch (Exception e1) {return e1 ;}@ Overrideprotected void onPostExecute (Exception exception Exception) {super. onPostExecute (Ti On); try {// here use try {} catch {} to catch all exceptions. When the onHttpRequestSuccess callback in the Activity encounters various exceptions, such as json parsing exceptions or null pointers, all exceptions can be caught here, instead, you do not have to judge the null if (exception = null) {if (listener! = Null) listener. onHttpRequestSuccess (requestCode, code, datajson);} else {if (listener! = Null) listener. onHttpRequestError (code, exception) ;}} catch (Throwable e) {e. printStackTrace ();} specify Parameter .exe cute ();} public static class Parameter {public final String key; public final String value; public Parameter (String key, String obj) {super (); this. key = key; this. value = obj ;}/ *** the network request end callback interface is in the ui thread, you can directly operate the ui control ** @ author Young **/public interface OnHttpResponseListener {/*** @ param requestCode * Request Code, custom, when a single Activity initiates multiple network requests in the form of an interface, is the status of each request different? * @ param json may be a json or a common string, the data format returned by each url interface may be different. Special treatment is required **/public void onHttpRequestSuccess (int requestCode, int serverResultCode, String json);/*** @ param requestCode * request code, custom: when multiple network requests are initiated through an interface in the same Activity, do you need to identify the status of each request * @ param exception * request exception */public void onHttpRequestError (int requestCode, exception exception );}}



Package com. example. sax; import java. util. list; import com. alibaba. fastjson. JSON;/*** Alibaba json encapsulation class * prevents parsing exceptions * @ author Young **/public Class Json {// parseObject (String text, class <PersonalInfoDO> clazz) public static <T> T parseObject (String text, Class <T> clazz) {try {return JSON. parseObject (text, clazz);} catch (Exception e) {e. printStackTrace ();} return null;} // JSON. toJSONStringpublic static String toJSONString (Object obj) {try {return JSON. toJSONString (obj);} catch (Exception e) {e. printStackTrace ();} return null;} // JSON. toJSONString // public static <T> String toJSONString (List <T> list) {/// try {// return JSON. toJSONString (list); //} catch (Exception e) {//} // return null; //} // JSON. parseArray (json, NearbyCraftsManDO. class); public static <T> List <T> parseArray (String text, Class <T> clazz) {try {return JSON. parseArray (text, clazz);} catch (Exception e) {e. printStackTrace ();} return null ;}}













Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.