The directory structure
build.gradle
dependencies { compile fileTree(dir: 'libs', include: [' *. Jar ']) testCompile junit: junit: '4.12' compile 'com. Android. Support: appcompat - v7:24.0.0' compile 'com. Orhanobut: logger: 1.8 the compile' IO. Reactivex: rxjava: 1.1.7 'compile' IO. Reactivex: rxandroid: 1.2.1 'compile 'com. Squareup. Retrofit2: retrofit: 2.1.0' compile 'com. Google. Code. Gson: gson: 2.7' compile 'com. Squareup. Retrofit2: converter - gson: 2.1.0' compile 'com. Squareup. Retrofit2: adapter - rxjava: 2.1.0'}Copy the code
Rxjava+Retrofit unified Http encapsulation
HttpService
Retrofit the configuration of the
Public interface HttpService {/** * @param waypoints; /** @param waypoints; Two or more points need to be passed in. Use "; "between two dots. The longitude and latitude of a single point are separated by ", "; For example: waypoints = 118 * 77147503233,32.054128923368; 116.3521416286, 39.965780080447; ,39.965780080447 * 116 * 28215586757 * @ @ param ak param output * @ return * / @ FormUrlEncoded @ POST (" short?" ) Observable>> getDistance(@Field("waypoints") String waypoints, @Field("ak") String ak, @Field("output") String output); }Copy the code
HttpUtil
Retrofit and Rxjava are combined to encapsulate network request classes
Public class HttpUtil {/** * Timeout */ private static final int DEFAULT_TIMEOUT = 10; /** * retrofit */ private Retrofit retrofit; /** * private HttpService HttpService; public HttpService getHttpService() { return httpService; } private HttpUtil() {// Create an okHttpClient.builder httpClientBuilder = new okHttpClient.builder (); httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); / / add the iterator httpClientBuilder. AddInterceptor (new LoggerInterceptor ()); retrofit = new Retrofit.Builder() .client(httpClientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(StaticCode.BASE_URL) .build(); httpService = retrofit.create(HttpService.class); } private static class SingletonHolder {private static final HttpUtil INSTANCE = new HttpUtil(); } public static HttpUtil getInstance() {return singletonholder.instance; } /** * public Observable packageObservable(Observable Observable) {return observable.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } /** * @param Observable */ public Subscription sendHttp(Observable, HttpSubscriber listener) { return packageObservable(observable) .subscribe(listener); } /** * @param Observable */ public Subscription sendHttpWithMap(Observable, HttpSubscriber listener) { return observable.compose(this.applySchedulers()) .subscribe(listener); } /** * Observable transform ** @param * @return */ Observable. T> applySchedulers() { return new Observable.Transformer, T>() { @Override public Observable call(Observable> baseHttpResultObservable) { return baseHttpResultObservable.map(new HttpFunc()) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }}; } /** * private class HttpFunc implements Func1, ** private class HttpFunc implements Func1, T> {@override public T call(BaseHttpResult BaseHttpResult) {if (! baseHttpResult.getStatus().equals(StaticCode.HTTP_RESPONSE_SUCCESS)) throw new RuntimeException(baseHttpResult.getStatus()); return baseHttpResult.getResults(); }}}Copy the code
LoggerInterceptor
Increases in log printing and request headers
public class LoggerInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request().newBuilder().addHeader("version", "1.0"). The addHeader (" clientSort ", "android"). The addHeader (" Charset ", "utf-8"). The build (); printRequestLog(originalRequest); Response response = null; Response = chain.proceed(originalRequest); printResult(response); } catch (SocketTimeoutException e) {// there is no other good method for crash. } return response; } /** * Prints Request logs ** @param originalRequest * @return * @throws IOException */ private void printRequestLog(Request) originalRequest) throws IOException { FormBody.Builder formBuilder = new FormBody.Builder(); String msg = originalRequest.url() + "\n"; RequestBody oidBody = originalRequest.body(); if (oidBody instanceof FormBody) { FormBody formBody = (FormBody) oidBody; for (int i = 0; i < formBody.size(); i++) { String name = URLDecoder.decode(formBody.encodedName(i), "utf-8"); String value = URLDecoder.decode(formBody.encodedValue(i), "utf-8"); if (! TextUtils.isEmpty(value)) { formBuilder.add(name, value); msg += name + " = " + value + "\n"; } } } Logger.i(msg); } /** * Prints returned logs ** @param response * @throws IOException */ private void printResult(response response) throws IOException { ResponseBody responseBody = response.body(); BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset UTF8 = Charset.forName("UTF-8"); MediaType contentType = responseBody.contentType(); if (contentType ! = null) { UTF8 = contentType.charset(UTF8); } String a = buffer.clone().readString(UTF8); Logger.i(a); }}Copy the code
BaseHttpResult
public class BaseHttpResult { public String status; private T results; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public T getResults() { return results; } public void setResults(T results) { this.results = results; }}Copy the code
Rxjava callback
Public abstract class HttpSubscriber extends Subscriber {/** * private int tag; public HttpSubscriber(int tag) { this.tag = tag; } @Override public void onCompleted() { _complete(); } @Override public void onError(Throwable e) { _complete(); onError(e.getMessage(), tag); } @Override public void onNext(T t) { onSuccess(t, tag); } public abstract void onSuccess(T t, int tag); public abstract void onError(String msg, int tag); public abstract void _complete(); }Copy the code
The addition of the Mvp
MvpView
public interface MvpView {
void showLoadingDialog();
void dismissLoadingDialog();
}
Copy the code
IBasePresenter
public interface IBasePresenter {
void subscribe();
void unsubscribe();
}
Copy the code
BasePresenter
Public abstract class BasePresenter implements IBasePresenter {
protected HttpUtil httpUtil = null; protected HttpService httpService = null; protected V baseView; /** * unsubscribe network request */ private CompositeSubscription scription; public BasePresenter(V view) { this.baseView = view; httpUtil = HttpUtil.getInstance(); httpService = httpUtil.getHttpService(); compositeSubscription = new CompositeSubscription(); } protected HttpSubscriber getProgressSubscriber(int tag) { baseView.showLoadingDialog(); return new HttpSubscriber(tag) { @Override public void onSuccess(T t, int tag) { BasePresenter.this.onSuccess(t, tag); } @Override public void onError(String msg, int tag) { BasePresenter.this.onError(msg, tag); } @Override public void _complete() { baseView.dismissLoadingDialog(); }}; } /** * @param observable * @param tag */ protected void sendHttp(Observable, int tag) { compositeSubscription.add(httpUtil.sendHttp(observable, getProgressSubscriber(tag))); } protected void sendHttp(Observable observable) { sendHttp(observable, 0); } /** */ param observable * @param tag */ protected void sendHttpWithMap(Observable, int tag) { compositeSubscription.add(httpUtil.sendHttpWithMap(observable, getProgressSubscriber (tag))); } protected void sendHttpWithMap(Observable observable) { sendHttpWithMap(observable, 0); } public abstract void onSuccess(T t, int tag); public abstract void onError(String msg, int tag); /** * unsubscribe public void unsubscribe() {if (compositeSubscription! = null && compositeSubscription.hasSubscriptions()) compositeSubscription.unsubscribe(); } /** ** addSubscription ** @param subscription */ public void addSubscription(subscription) {if (compositeSubscription == null) { compositeSubscription = new CompositeSubscription(); } compositeSubscription.add(subscription); }}Copy the code
Use the sample
MainActivity
Implement the View in the Activity
public class MainActivity extends AppCompatActivity implements MainContract.IMainView { private MainPre mainPre; private android.widget.TextView getDistance; private android.widget.TextView firstToSecondDistance; private android.widget.TextView secondToThreeDistance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.secondToThreeDistance = (TextView) findViewById(R.id.second_to_three_distance); this.firstToSecondDistance = (TextView) findViewById(R.id.first_to_second_distance); this.getDistance = (TextView) findViewById(R.id.get_distance); mainPre = new MainPre(this); getDistance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mainPre.subscribe(); }}); } @Override public void setFirstPointToSecondPointDistance(String distance) { firstToSecondDistance.setText(distance); } @Override public void setSecondPointToThreePointDistance(String distance) { secondToThreeDistance.setText(distance); } @override public void showLoadingDialog() {logger. e(" request started "); } @override public void dismissLoadingDialog() {Override public void dismissLoadingDialog(); }}Copy the code
MainContract
public class MainContract { /** * Created by huangweizhou on 16/8/10. */ public interface IMainView extends MvpView { / * * * the distance between the first and the second * * @ param short * / void setFirstPointToSecondPointDistance (String short); / * * * the distance between the second and third * * @ param short * / void setSecondPointToThreePointDistance (String short); }}Copy the code
MainPre
The View and parse type that are bound to presenter
public class MainPre extends BasePresenter> { public MainPre(MainContract.IMainView view) { super(view); } @Override public void onSuccess(List strings, int tag) { baseView.setFirstPointToSecondPointDistance(strings.get(0)); baseView.setSecondPointToThreePointDistance(strings.get(1)); } @Override public void onError(String msg, int tag) { Logger.e(msg); } @ Override public void the subscribe () {sendHttpWithMap (httpService. GetDistance (118.77147503233, 32.054128923368;" \ n "+" 116.3521416286, 39.965780080447; 116.28215586757, 39 \ n "+" 965780080447 ", "six cyepstfao1hsfgpseshrxa459p3tyt0", "json")); }}Copy the code
StaticCode
Public class StaticCode {/** * Java address */ public static final String BASE_URL = "http://api.map.baidu.com/telematics/v3/"; Public static final String HTTP_RESPONSE_SUCCESS = "Success"; /** * public static final String HTTP_RESPONSE_SUCCESS = "Success"; }Copy the code
The source address
Mvp-RxJava-Retrofit