RxJava+Retrofit公用请求二次封装

添加jar包

compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'

请求完毕数据回调接口

public interface HttpRequestCallback {
  public interface HttpRequestCallback {  /**
     * 获取数据
     *
     * @param sequest
     * @param type
     */
    void onResponse(String sequest, String type);

    /**
     * 获取数据失败
     *
     * @param exp
     */
    void onFailure(String exp);
}

共用http二次封装类

public class OkHttpUtils {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");//post请求编码
    private static OkHttpClient mOkHttpClient;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public static List<String> cookies = new ArrayList<>();

    /**
     * 获取数据接口
     *
     * @param context 上下文
     * @param action  服务器方法
     */
    public static Observable<String> postAsynHttp(final Context context, final String action, final FormBody.Builder formBody) {
        CheckConnect(context);
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                mOkHttpClient = new OkHttpClient().newBuilder().readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(10, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                        .build();
                MyLog.e(formBody.toString());
                try {
                    Request request = new Request.Builder().url(action).addHeader("cookie", String.valueOf(cookies)).post(formBody.build()).addHeader("cookie", String.valueOf(cookies)).build();
                    final Call call = mOkHttpClient.newCall(request);
                    //excute
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String str = response.body().string();
                            if (action.contains("system_login")) {
                                Headers headers = response.headers();
                                cookies = headers.values("Set-Cookie");
                            }
                            subscriber.onNext(str);
                            subscriber.onCompleted();
                        }
                    });
                } catch (IllegalArgumentException e) {
                    subscriber.onError(e);
                }
            }
        });
    }

    /**
     * 获取数据接口
     * Request request = new Request.Builder().url(action).get().build();
     *
     * @param context 上下文
     * @param action  服务器方法
     */
    public static Observable<String> getAsynHttp(final Context context, final String action) {
        CheckConnect(context);
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                mOkHttpClient = new OkHttpClient().newBuilder().readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(10, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                        .build();
                MyLog.e(action.toString());
                try {
                    Request request = new Request.Builder().url(action).addHeader("cookie", String.valueOf(cookies)).get().build();
                    final Call call = mOkHttpClient.newCall(request);
                    //excute
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String str = response.body().string();
                            if (action.contains("system_login")) {
                                Headers headers = response.headers();
                                cookies = headers.values("Set-Cookie");
                            }
                            subscriber.onNext(str);
                            subscriber.onCompleted();
                        }
                    });
                } catch (IllegalArgumentException e) {
                    subscriber.onError(e);
                }
            }
        });
    }

    /**
     * @param context         上下文
     * @param action          服務器方法
     * @param HttpType        接口類型
     * @param requestCallback 回調接口
     */
    public static void postAsynHttp_File(final Context context, MultipartBody.Builder builder, String action, final HttpRequestCallback requestCallback, final String HttpType) {
        CheckConnect(context);
        mOkHttpClient = new OkHttpClient();
        MultipartBody requestBody = builder.build();
        Request request = new Request.Builder().url(action).post(requestBody).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String exceptionCode = e.getLocalizedMessage();
                if ("java.net.SocketTimeoutException".equals(exceptionCode)) {
                    Toast.makeText(context, "数据获取超时", Toast.LENGTH_SHORT).show();
                } else if (exceptionCode
                        .contains("http.conn.ConnectTimeoutException")) {
                    Toast.makeText(context, "网络连接超时", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.getString("code").equals("200")) {
                        requestCallback.onResponse(str, HttpType);
                    } else {
                        requestCallback.onFailure(object.getString("msg"));
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    requestCallback.onFailure("数据解析异常!");
                } catch (JSONException e) {
                    requestCallback.onFailure("数据异常!");
                    e.printStackTrace();
                }
            }
        });
    }

    private static void CheckConnect(Context cont) {
        ConnectivityManager cm = (ConnectivityManager) cont.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {
            Toast.makeText(cont, "暂无网络连接,请连接网络!", Toast.LENGTH_SHORT).show();
            return;
        }
    }
}

处理数据的类共用

public class BigPresenter {
    HttpRequestCallback call;

    private static BigPresenter instance = null;

    private BigPresenter() {
    }

    public static BigPresenter getInstances() {
        if (null == instance) {
            instance = new BigPresenter();
        }
        return instance;
    }

    public void httpPost(final Context ext, final FormBody.Builder formBody, final String type, HttpRequestCallback call, final String action) {
        this.call = call;
        formBody.add("accountId", SPUtils.getString(ext, MyConstaints.ACCOUNTID, ""));//后期全部接口都要添加的参数不要找代码一个一个添加,直接添加就好了
        Observable<String> stringObservable = OkHttpUtils.postAsynHttp(ext, action, formBody).subscribeOn(Schedulers.io());
        MyLog.e(action);
        stringObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        MyLog.e("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        onErrer(e.getLocalizedMessage(), ext);
                    }

                    @Override
                    public void onNext(String s) {
                        MyLog.e("onNext" + s);
                        MyLog.e(s);
                        onSuccess(s, type, ext);
                    }
                });
    }

    public void httpPostLogin(final Context ext, FormBody.Builder formBody, final String type, HttpRequestCallback call, String action, String accountId) {
        this.call = call;
        formBody.add("accountId", accountId);
        formBody.add("language", SPUtils.getString(ext, MyConstaints.LANGUAGE, ""));
        Observable<String> stringObservable = OkHttpUtils.postAsynHttp(ext, action, formBody).subscribeOn(Schedulers.io());
        stringObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        MyLog.e("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        onErrer(e.getLocalizedMessage(), ext);
                    }

                    @Override
                    public void onNext(String s) {
                        MyLog.e("onNext" + s);
                        MyLog.e(s);
                        onSuccessLogin(s, type, ext);
                    }
                });
    }

    private void onErrer(String parameter, Context context) {
        if ("java.net.SocketTimeoutException".equals(parameter)) {
            call.onFailure(context.getResources().getString(R.string.timeout_exception));
        } else if (parameter.contains("http.conn.ConnectTimeoutException")) {
            call.onFailure(context.getResources().getString(R.string.connecttimeout));
        } else if (parameter.contains("Failed")) {
            call.onFailure("服务端连接失败!");
        } else if (parameter.contains("failed")) {
            call.onFailure("服务端连接失败!");
        } else {
            call.onFailure(parameter);
        }
    }

    private void onSuccess(String parameter, String type, Context context) {
        try {
            JSONObject object = new JSONObject(parameter);
            if (object.getString("status").equals("200")) {
                call.onResponse(parameter, type);
            } else {
                call.onFailure(object.getString("msg"));
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            call.onFailure(context.getResources().getString(R.string.jsonsyntaxexception));
        } catch (JSONException e) {
            call.onFailure(context.getResources().getString(R.string.jsonexception));
            e.printStackTrace();
        }
    }

    private void onSuccessLogin(String parameter, String type, Context context) {
        try {
            JSONObject object = new JSONObject(parameter);
            if (object.getString("success").equals("true")) {
                call.onResponse(parameter, type);
            } else {
                call.onFailure(object.getString("message"));
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            call.onFailure(context.getResources().getString(R.string.jsonsyntaxexception));
        } catch (JSONException e) {
            call.onFailure(context.getResources().getString(R.string.jsonexception));
            e.printStackTrace();
        }
    }

    public void httpGet(final Context ext, final String type, HttpRequestCallback call, String action) {
        this.call = call;
        Observable<String> stringObservable = OkHttpUtils.getAsynHttp(ext, action).subscribeOn(Schedulers.io());
        stringObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        MyLog.e("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e == null) {
                            onErrer("服务端异常!", ext);
                        } else {
                            onErrer(e.getLocalizedMessage(), ext);
                        }
                    }

                    @Override
                    public void onNext(String s) {
                        MyLog.e("onNext" + s);
                        MyLog.e(s);
                        onSuccess(s, type, ext);
                    }
                });
    }

    public RequestInterface retrofitRequest(String action, Context context, String url) {
        Retrofit retrofit = new Retrofit.Builder().client(genericClient()).baseUrl(url + action).addConverterFactory(ScalarsConverterFactory.create()).build();
        MyLog.e(SPUtils.getString(context, url, "") + action);
        return retrofit.create(RequestInterface.class);
    }

    public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().addHeader("cookie", String.valueOf(OkHttpUtils.cookies)).build();
                        return chain.proceed(request);
                    }
                })
                .build();
        return httpClient;
    }


    public void httpRetrofit(final Context ext, final String type, HttpRequestCallback call, Call<String> Responsecall) {
        this.call = call;
        Observable<String> stringObservable = OkHttpUtilsRetrofit.postAsynHttp(ext, Responsecall).subscribeOn(Schedulers.io());
        if (stringObservable == null) {
            return;
        }
        stringObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        MyLog.e("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        onErrer(e.getLocalizedMessage(), ext);
                    }

                    @Override
                    public void onNext(String s) {
                        MyLog.e("onNext" + s);
                        onSuccess(s, type, ext);
                    }
                });
    }
}

Retrofit注解方式拼接数据

public interface RequestInterface {
    /**
     * @param LineCode
     * @param ClientCode
     * @return
     */
    @GET("{LineCode}/{ClientCode}")
    Call<String> getOrderByLine(@Path("LineCode") String LineCode, @Path("ClientCode") String ClientCode);

    /**
     * @param Order
     * @param Id
     * @param Quantity
     * @param ClientCode
     * @param UpdateBy
     * @return
     */
    @POST("{MaterialDeliveryOrder}/{Id}/{Quantity}/{UpdateBy}/{ClientCode}")
    Call<String> editNumber(@Path("MaterialDeliveryOrder") String Order, @Path("Id") String Id, @Path("Quantity") String Quantity, @Path("UpdateBy") String UpdateBy, @Path("ClientCode") String ClientCode);

    /**
     * @param Order
     * @param Id
     * @param UpdateBy
     * @param ClientCode
     * @return
     */
    @POST("{MaterialDeliveryOrder}/{Id}/{UpdateBy}/{ClientCode}")
    Call<String> delete(@Path("MaterialDeliveryOrder") String Order, @Path("Id") String Id, @Path("UpdateBy") String UpdateBy, @Path("ClientCode") String ClientCode);

    /**
     * 获取菜单
     *
     * @param accountId
     * @param parentId
     * @param language
     * @param clientCode
     * @return
     */
    @GET("{accountId}/{parentId}/{language}/{clientCode}")
    Call<String> getMenu(@Path("accountId") String accountId, @Path("parentId") String parentId, @Path("language") String language, @Path("clientCode") String clientCode);

}

调起接口

private final String GETMEN = "GETMEN";
private final String LOGIN = "LOGIN";

//根据后台的方式二者选其一
//请求方式二
private void initMenu() {
    RequestInterface edit = BigPresenter.getInstances().retrofitRequest("findResourceByParentId/", this, url);
    BigPresenter.getInstances().httpRetrofit(this, GETMEN, this, edit.getMenu(accountid, "0", language, clientcode));
}

//请求方式一
private void spandTimeMethod(String serverURL, String accountIds, String password, String clientCode) {
    FormBody.Builder formBody = new FormBody.Builder();
    formBody.add("passWord", tool.md5(password));
    formBody.add("appType", "MS");
    formBody.add("clientCode", clientCode);
    BigPresenter.getInstances().httpPostLogin(LoginActivity.this, formBody, LOGIN, this, "http://" + serverURL + "/system_login", accountIds);
}

@Override
public void onResponse(String sequest, String type) {

    switch (type) {
        case GETMEN:
            Gson gson = new Gson();'
            break;
    }
}

@Override
public void onFailure(String exp) {
    alertNoTitle(R.drawable.err, exp, null, null, true);
}


回调参数在同一接口处理,阅读性会好一点,维护起来比较简单



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shu_quan/article/details/79975866
个人分类: 移动开发
上一篇Android 图片加载带进度条的ImageView
下一篇Java 打印回形二维数组
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭