Application of Retrofit in projects and Application of Retrofit projects
Define an annotation to serialize bean Fields
Import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** used for Gson naming policy annotation */@ incluented @ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. FIELD) public @ interface ParamName {String value ();}
Annotation of the bean to be transmitted over the network:
public class requestBean implements Parcelable {public static final int RESPONSE_OK = 1;@ParamName("id") private String mId;@ParamName("name") private String mName;@ParamName("result")private int mResult;@ParamName("message")private String mMessage;public int getResult() {return mResult;}public String getMessage() {return mMessage;}public String getId() {return mId;} public String getName() { return mName; }public boolean succeed() {return getResult() == RESPONSE_OK;}}
Encapsulate the defined annotation into gson
Import com. google. gson. fieldNamingPolicy; import com. google. gson. fieldNamingStrategy; import com. google. gson. gson; import com. google. gson. gsonBuilder; import com. newandbie. privatecustomize. config; import com. newandbie. privatecustomize. annotate. paramName; import com. newandbie. privatecustomize. model. gender; import java. lang. reflect. field;/*** custom Gson */public class GsonUtils {public static Gson newInstan Ce () {GsonBuilder builder = new GsonBuilder (); builder. setFieldNamingStrategy (new AnnotateNaming (); return builder. create ();} private static class AnnotateNaming implements FieldNamingStrategy {@ Override public String translateName (Field field) {ParamName a = Field. getAnnotation (ParamName. class); return! = Null? A. value (): FieldNamingPolicy. IDENTITY. translateName (field );}}}
Import com. squareup. okhttp. cache; import com. squareup. okhttp. okHttpClient; import android. content. context; import java. io. file; import java. io. IOException; import java. util. concurrent. timeUnit;/*** OkHttpClient custom tool class */public class OkHttpUtils {private static OkHttpClient singleton; public static OkHttpClient getInstance (Context context) {if (singleton = null) {synchronized (OkHttpUtils. class) {if (singleton = null) {File cacheDir = new File (context. getCacheDir (), Config. RESPONSE_CACHE); singleton = new OkHttpClient (); try {singleton. setCache (new Cache (cacheDir, Config. RESPONSE_CACHE_SIZE);} catch (IOException e) {e. printStackTrace ();} singleton. setConnectTimeout (Config. HTTP_CONNECT_TIMEOUT, TimeUnit. MILLISECONDS); singleton. setReadTimeout (Config. HTTP_READ_TIMEOUT, TimeUnit. MILLISECONDS) ;}}return singleton ;}}
Define the fit tool to configure the above two tools to paifitutils
Import android. content. context; import into fit. restAdapter; import pull fit. client. okClient; import into fit. converter. gsonConverter; public class extends fitutils {private static RestAdapter singleton; public static <T> T createApi (Context context, Class <T> clazz) {if (singleton = null) {synchronized (synchronized fitutils. class) {if (singleton = null) {RestAdapter. builder builder = new RestAdapter. build Er (); builder. setEndpoint (IP address); // sets the remote address builder. setConverter (new GsonConverter (GsonUtils. newInstance (); builder. setClient (new OkClient (OkHttpUtils. getInstance (context); builder. setLogLevel (Config. DEBUG? RestAdapter. LogLevel. FULL: RestAdapter. LogLevel. NONE); singleton = builder. build () ;}} return singleton. create (clazz );}}
The toolset is ready,
Put 'fit fit' in the parent class for the subclass to call
Import into fit. callback; import into fit. optional fiterror; import invalid fit. client. response;/*** interface base class */public class BaseActivity extends ActionBarActivity {.... /*** create an API instance ** @ param cls Api definition Class type * @ param <T> type * @ return API instance */public <T> T createApi (Class <T> cls) {return optional fitutils. createApi (this, cls);} public static abstract class ActivityCallback <T> implements Callback <T> {<span styl E = "white-space: pre"> </span> // soft reference, cache reference object private final WeakReference <BaseActivity> mRef; public ActivityCallback (BaseActivity activity) {mRef = new WeakReference <BaseActivity> (activity);} public Activity getActivity () {return mRef. get () ;}@ Override public void failure (writable fiterror error) {final BaseActivity activity = mRef. get (); Response response = error. getResponse (); if (response! = Null) {Toast. makeText (activity, activity. getString (R. string. server_error), Toast. LENGTH_SHORT ). show (); Log. e (getLogTag (), "code:" + response. getStatus () + ", reason:" + response. getReason (); error. printStackTrace ();}}}.....}
Define the following rest api interface. This interface defines a function ask, which will access the server's // ellassy/teacher/ask through the HTTP post request
And encapsulate the returned results as the requestBean Java object to return.
import retrofit.Callback;import retrofit.http.Field;import retrofit.http.FormUrlEncoded;import retrofit.http.Header;import retrofit.http.POST;public interface ExpertApi { @FormUrlEncoded @POST("/ellassy/teacher/ask") void ask(@Header("token") String token, @Field("member_id") String memberId, @Field("title") String title, @Field("description") String description, @Field("teacher_id") String expertId, Callback<requestBean> cb);}
The rect client requests the server
Import android. content. context; import android. content. intent; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. toast; import into fit. client. response; public class AskActivity extends implements View. onClickListener {private ExpertApi mExpertApi ;//... @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState );//... mExpertApi = createApi (ExpertApi. class) ;}@ Override public void onClick (View v ){//... call the rest interface mExpertApi. ask (getToken (), mUserInfo. getId (), title, question, mExpertId, new AskCallback (AskActivity. this);} // The callback interface returns the private static final class AskCallback extends ActivityCallback <requestBean> {public AskCallback (AskActivity activity) {super (activity );} @ Override public void success (requestBean requestbean, Response response) {AskActivity activity = (AskActivity) getActivity (); if (requestbean. succeed () {Toast. makeText (activity, "data returned successfully", Toast. LENGTH_SHORT ). show (); activity. finish ();} else {Toast. makeText (activity, askResponse. getMessage (), Toast. LENGTH_SHORT ). show ();}}}}