How to create a third-party network engine and chain a third-party
How to create a third-party network engine through chained calls
First, IHttpEnigne
Public interface IHttpEngine {// get method void get (Context context, String url, Map
Params, EngineCallBack callBack); // post method void post (Context context, String url, Map
Params, EngineCallBack callBack); // download a file // upload a file // https certificate}
HttpUtils
Public class HttpUtils {// What does a chained call need to pass? // url private String mUrl; // Request Method private int mType = GET_TYPE; private static final int POST_TYPE = 0x0011; private static final int GET_TYPE = 0x0010; private Context mContext; private Map
MParams; // do not allow external calls to private HttpUtils (Context context) {this. mContext = context; mParams = new HashMap <> () ;}public static HttpUtils with (Context context) {return new HttpUtils (context );} // url public HttpUtils url (String url) {this. mUrl = url; return this ;}// get request public HttpUtils get () {mType = GET_TYPE; return this ;}// post public HttpUtils post () {mType = GET_TYPE; return this;} // Add the public HttpUtils addParams (String key, String value) {mParams. put (key, value); return this;} public HttpUtils addParams (Map
Params) {mParams. putAll (params); return this;} // callBack method public void execture (EngineCallBack callBack) {if (callBack = null) {callBack = EngineCallBack. DEFAULT_CALL_BACK;} if (mType = GET_TYPE) {get (mUrl, mParams, callBack);} if (mType = POST_TYPE) {post (mUrl, mParams, callBack );}} public void execture () {execture (null);} // The default value is OkHttp engine private static IHttpEngine mHttpEngine = new OkHttpEngine (); public HttpUtils () {} // call public static void init (IHttpEngine httpEngine) in Application {mHttpEngine = httpEngine;}/*** switch engine */public HttpUtils exchangeEngine (IHttpEngine httpEngine) {mHttpEngine = httpEngine; return this;} private void get (String url, Map
Params, EngineCallBack callBack) {mHttpEngine. get (mContext, url, params, callBack);} private void post (String url, Map
Params, EngineCallBack callBack) {mHttpEngine. post (mContext, url, params, callBack);}/*** splicing parameter */public static String jointParams (String url, Map
Params) {if (params = null | params. size () <= 0) {return url;} StringBuffer stringBuffer = new StringBuffer (url); if (! Url. contains ("? ") {StringBuffer. append ("? ");} Else {if (! Url. endsWith ("? ") {StringBuffer. append (" & ") ;}} for (Map. Entry
Entry: params. entrySet () {stringBuffer. append (entry. getKey () + "=" + entry. getValue () + "&");} stringBuffer. deleteCharAt (stringBuffer. length ()-1); return stringBuffer. toString ();}/*** obtain the generic parameter through reflection */public static Class
AnalysisClazzInfo (Object object) {Type genType = object. getClass (). getGenericSuperclass (); // obtain the parent class Type with generics [] params = (ParameterizedType) genType ). getActualTypeArguments (); return (Class
) Params [0] ;}}
EngineCallBack
Public interface EngineCallBack {// error public void onError (Exception e); // success data {"", ""} success failed data "" public void onSuccess (String result ); // callback method before method execution public void onPreExceture (Context context, Map
Params); // default callback interface public EngineCallBack DEFAULT_CALL_BACK = new EngineCallBack () {@ Override public void onError (Exception e) {}@ Override public void onSuccess (String result) {}@ Override public void onPreExceture (Context context, Map
Params ){}};}
OKHttpEngine
Public class OkHttpEngine implements IHttpEngine {private OkHttpClient mOkHttpClient = new OkHttpClient (); @ Override public void get (Context context, String url, Map
Params, final EngineCallBack callBack) {url = HttpUtils. jointParams (url, params); Log. e ("Get Request Path:", url); Request. builder requestBuilder = new Request. builder (). url (url ). tag (context); // can be omitted. The default value is GET Request request = requestBuilder. build (); mOkHttpClient. newCall (request ). enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {callBack. onError (e) ;}@ Override public void onResponse (Call call, Response response) throws IOException {String resultJson = response. body (). string (); callBack. onSuccess (resultJson); Log. e ("Get return result:", resultJson) ;}) ;}@ Override public void post (Context context, String url, Map
Params, final EngineCallBack callBack) {final String jointUrl = HttpUtils. jointParams (url, params); // print Log. e ("Post Request Path:", jointUrl); RequestBody requestBody = appendBody (params); request Request = new Request. builder (). url (url ). tag (context ). post (requestBody ). build (); mOkHttpClient. newCall (request ). enqueue (new Callback () {@ Override public void onFailure (okhttp3.Call call, IOException e) {callBack. onError (e) ;}@ Override public void onResponse (okhttp3.Call call, Response response) throws IOException {// neither of the two methods is in the main thread String result = response. body (). string (); Log. e ("Post returned results:", jointUrl); callBack. onSuccess (result) ;}}) ;}/ *** assemble the post request parameter body */protected RequestBody appendBody (Map
Params) {MultipartBody. builder builder = new MultipartBody. builder (). setType (MultipartBody. FORM); addParams (builder, params); return builder. build ();} // Add the private void addParams (MultipartBody. builder builder, Map
Params) {if (params! = Null &&! Params. isEmpty () {for (String key: params. keySet () {builder. addFormDataPart (key, params. get (key) + ""); Object value = params. get (key); if (value instanceof File) {// process the File --> Object File file File = (File) value; builder. addFormDataPart (key, file. getName (), RequestBody. create (MediaType. parse (guessMimeType (file. getAbsolutePath (), file);} else if (value instanceof List) {// indicates that the List set is submitted. try {List
ListFiles = (List
) Value; for (int I = 0; I <listFiles. size (); I ++) {// get File file = listFiles. get (I); builder. addFormDataPart (key + I, file. getName (), RequestBody. create (MediaType. parse (guessMimeType (file. getAbsolutePath (), file) ;}} catch (Exception e) {e. printStackTrace () ;}} else {builder. addFormDataPart (key, value + "") ;}}}/*** guess file type */private String guessMimeType (String path) {FileNameMap fileNameMap = URLConnection. getFileNameMap (); String contentTypeFor = fileNameMap. getContentTypeFor (path); if (contentTypeFor = null) {contentTypeFor = "application/octet-stream" ;}return contentTypeFor ;}}
1. There are many identical parameters when requesting the network. At this time, we can add the same parameters before the method execution.
2. every time we switch back to Json, We can't directly use generics, because json data will be transmitted in the background when the call is successful, but when the call fails, it may be a string.
HttpCallBack
Public abstract class HttpCallBack
Implements EngineCallBack {@ Override public void onPreExceture (Context context, Map
Params) {// Add public parameters to the project. // The project name context params is related to the project business logic. put ("app_name", "joke_essay"); params. put ("version_name", "5.7.0"); params. put ("ac", "wifi"); params. put ("device_id", "30036118478"); params. put ("device_brand", "Xiaomi"); params. put ("update_version_code", "5701"); params. put ("manifest_version_code", "570"); params. put ("longpolling", "113.000366"); params. put ("latitude", "28.171377"); params. put ("device_platform", "android"); onPreExecute ();} protected void onPreExecute () {}@ Override public void onSuccess (String result) {Gson gson = new Gson (); T objectResult = (T) gson. fromJson (result, HttpUtils. analysisClazzInfo (this); onSuccess (objectResult);} public abstract void onSuccess (T result );}
Use
HttpUtils. with (this ). url ("https://is.snssdk.com/2/essay/discovery/v3 "). addParams ("iid", "6152551759 "). addParams ("aid", "7 "). exchangeEngine (new OkHttpEngine ()). execture (new HttpCallBack
() {@ Override public void onError (Exception e) {}@ Override public void onSuccess (DiscoverListResult result) {Log. e ("TAG", "name -->" + result. getData (). getCategories (). getName () ;}@ Override public void onPreExecute () {super. onPreExecute (); // progress bar, etc }})