Retrofit2 tutorial and Android Network Architecture (original), retrofit2android

Source: Internet
Author: User

Retrofit2 tutorial and Android Network Architecture (original), retrofit2android

Squareup has been releasing movie fit2 for some time. The current version is stable and there is no big pitfall. The tutorial on the network is either too simple, just a Demo; or some fall, or the reusability is poor, so I write a tutorial (alex9xu@hotmail.com) for your reference.

 

1. First introduce dependencies in build. gradle

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Note that logging is used to output the Log of network interaction, which is extremely useful for development and debugging. Previously, mongofit2 was abandoned for a long time because it could not output logs. Various experts have implemented several Log printing methods, and now there is an official one.

 

2. This is a tool class

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;import com.alex9xu.test.config.AppConfigInterface;import java.io.IOException;
/** * Created by Alex9Xu@hotmail.com on 2016/7/13 */public class RetrofitBase {    private static Retrofit mRetrofit;    public static Retrofit retrofit() {        if (mRetrofit == null) {            OkHttpClient client;            // Notice: The only differ of debug is: HttpLoggingInterceptor
            if(!AppConfigInterface.isDebug) {                client = new OkHttpClient.Builder()                        .addInterceptor(new Interceptor() {                            @Override
                            public Response intercept(Chain chain) throws IOException {                                Request original = chain.request();
                                HttpUrl originalHttpUrl = original.url();
                                HttpUrl url = originalHttpUrl.newBuilder()                                        .addQueryParameter("Id", "123456")                                        .addQueryParameter("deviceType", "0")                                        .build();
                                // Request customization: add request headers
                                Request.Builder requestBuilder = original.newBuilder()                                        .url(url);
                                Request request = requestBuilder.build();
                                return chain.proceed(request);                            }                        })                        .build();
            } else {                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                client = new OkHttpClient.Builder()                        .addInterceptor(logging)                        .addInterceptor(new Interceptor() {                            @Override
                            public Response intercept(Chain chain) throws IOException {                                Request original = chain.request();
                                HttpUrl originalHttpUrl = original.url();
                                HttpUrl url = originalHttpUrl.newBuilder()                                        .addQueryParameter("Id", "123456")                                        .addQueryParameter("deviceType", "0")                                        .build();
                                // Request customization: add request headers
                                Request.Builder requestBuilder = original.newBuilder()                                        .url(url);
                                Request request = requestBuilder.build();
                                return chain.proceed(request);                            }                        })                        .build();
            }            mRetrofit = new Retrofit.Builder()                    .baseUrl(AppConfigInterface.BASE_COM_URL)                    .addConverterFactory(GsonConverterFactory.create())                    .client(client)                    .build();        }        return mRetrofit;    }}

To explain:

(1) Use addInterceptor to print logs and add multiple public parameters.

(2) Except HttpLoggingInterceptor, there is no difference between the test and the formal one. Use global variables to determine whether the Log is in the formal environment. If the Log is in the formal environment, no network interaction logs are output.

(3) You can add multiple public parameters in the form of addQueryParameter ("deviceType", "0"), so that all requests will carry this parameter.

(4) hereBASE_COM_URLIs the form of http://test.hello.com.

 

3. Usage:

 

(1) write the interface first

import android.support.v4.util.ArrayMap;import com.alex9xu.test.config.AppConfigInterface;import com.alex9xu.test.model.ClassifyListResult;import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;/** * Created by Alex9Xu@hotmail.com on 2016/7/14 */
public interface ClassifyApi {    @GET(AppConfigInterface.CLASSIFYLIST)    Call<ClassifyListResult> getClassify(@QueryMap ArrayMap<String,String> paramMap);}

Parameters submitted through Post are stored in Map. You can add multiple sets of parameters. Note: I used ArrayMap, which is a unique form in Android. The memory usage is only about of that of HashMap.

String CLASSIFYLIST = "query/classify.html";

 

(2) write the return value structure again

import com.alex9xu.test.base.BaseResponse;import com.alex9xu.test.model.entity.ClassfiyBean;import java.util.List;/** * Created by Alex9Xu@hotmail.com on 2016/7/14 */public class ClassifyListResult extends BaseResponse {    private DataEntity data;    public DataEntity getData() {        return data;    }    public static class DataEntity {        private List<ClassfiyBean> classifyList;        public List<ClassfiyBean> getClassifyList() {            return classifyList;        }    }}

 

/** * Created by Alex9Xu@hotmail.com on 2016/7/14 */public class ClassfiyBean {    private String icon;    private String name;    public String getIcon() {        return icon;    }    public String getName() {        return name;    }}

The returned data is written in the preceding format to facilitate reuse.

 

(3) Call

import com.alex9xu.test.model.ClassifyListResult;import com.alex9xu.test.model.entity.ClassfiyBean;import com.alex9xu.test.net.ClassifyApi;import com.alex9xu.test.net.RetrofitBase;
/** * Created by Alex9Xu@hotmail.com on 2016/7/14 */
public class MainActivity extends AppCompatActivity{
  ...
private void getData() {    ArrayMap<String,String> paramMap = new ArrayMap<>();
    paramMap.put("version", "1.0");
    paramMap.put("uid", "654321");
    ClassifyApi classifyApi = RetrofitBase.retrofit().create(ClassifyApi.class);
    Call<ClassifyListResult> call = classifyApi.getClassify(paramMap);
    call.enqueue(new Callback<ClassifyListResult>() {        @Override
        public void onResponse(Call<ClassifyListResult> call, Response<ClassifyListResult> response) {            LogHelper.d(TAG, "getClassify, Suc");
            LogHelper.d(TAG, "getClassify = " + response.body());
            if(null != response.body() && null != response.body().getData()) {                List<ClassfiyBean> list = response.body().getData().getClassifyList();
                if(null != list && list.size()>0) {                    mTvwDisplay.setText(list.get(0).getName());
                }            }        }        @Override
        public void onFailure(Call<ClassifyListResult> call, Throwable t) {            LogHelper.e(TAG, "getClassify, Fail");
        }    });
}
...

 

Will be spliced into a https://test.hello.com/query/classify.html? Uid = 654321 & version = 1.0 & Id = 123456 & deviceType = 0. Note that two of them are public parameters.

 

Okay, so that it can run normally.

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.