OkhttpUtils封装

 https://www.cnblogs.com/whycxb/p/7636249.html

MyApplication 进行初始化
package com.example.administrator.myokhttp;

import android.app.Application;
import android.content.Context;

import com.example.administrator.myokhttp.utils.PrefManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhy on 15/8/25.
 */
public class MyApplication extends Application {
    /**
     * 系统上下文
     */
    private static Context mAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
        PrefManager.initializeInstance(getApplicationContext(), "sssss");

//        Stetho.initializeWithDefaults(this);
        initOkHttp();//配置OkhttpClient
    }

    /**
     * 获取系统上下文:用于ToastUtil类
     */
    public static Context getAppContext() {
        return mAppContext;
    }

    private void initOkHttp() {

//        ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);

//        CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG",true))
                .addNetworkInterceptor(new Interceptor() {//自定义拦截器
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request  = chain.request();
                        //配置统一的头
                        Request  newRequest     = request.newBuilder()
//                                .addHeader("","")
                                .addHeader("token", PrefManager.getInstance().get().getString(ServerApi.SP_TOKEN,"")).build();
                        return  chain.proceed(newRequest);
                    }
                })
//                .addNetworkInterceptor( new StethoInterceptor())//增加Stetho拦截器,用于调试
//                .cookieJar(cookieJar1)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }
}
package com.example.administrator.myokhttp;

import android.os.Build;
import android.util.Log;

import com.example.administrator.myokhttp.utils.PrefManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;


/**
 * @Created HaiyuKing
 * @Used 登录界面相关接口
 */
public class UserNet  {

    private static UserNet instance = null;

    public static synchronized UserNet Instance() {
        if (instance == null)
            instance = new UserNet();
        return instance;
    }

    /**
     * yzm
     */
    public void imageCode(BitmapCallback callback)
            throws Exception {
        OkHttpUtils
                .get()
                .url(ServerApi.URL_imageCode)
                .id(100)
                .tag(MyApplication.getAppContext())
                .build()
                .execute(callback);
    }

    /**
     * 获取手机验证码
     */
    public void mobileCode(String phone, String imageCode,StringCallback callback)
            throws Exception {
        OkHttpUtils
                .get()
                .url(ServerApi.URL_mobileCode+ "?mobile=" + phone + "&imageCode=" + imageCode)
                .id(100)
                .tag(MyApplication.getAppContext())
                .build()
                .execute(callback);
    }
    /**
     * 获取手机验证码
     */
    public void app_login(String phone, String mobileCode,StringCallback callback)
            throws Exception {
        OkHttpUtils
                .get()
                .url(ServerApi.URL_app_login+  "?mobile=" + phone + "&mobileCode=" + mobileCode)
                .id(100)
                .tag(MyApplication.getAppContext())
                .build()
                .execute(callback);
    }

    /**
     * 获取手机验证码
     */
    public void mobile_info(StringCallback callback)
            throws Exception {
        OkHttpUtils
                .post()
//                .addHeader("token", PrefManager.getInstance().get().getString(ServerApi.SP_TOKEN,""))
                .url(ServerApi.URL_mobile_info)
                .id(100)
                .tag(MyApplication.getAppContext())
                .addParams("mobileInfo", Build.ID)
                .build()
                .execute(callback);
    }
}



/*
//https://www.cnblogs.com/whycxb/p/7636249.html
//Post请求
public String LoginApi(String userName, String password,StringCallback callback)
            throws Exception {
        String result = "";
        OkHttpUtils
                .post()
                .url(getSpcyUrl(ServerApi.LOGIN_URL))
                .addParams("user.userName", userName)
                .addParams("user.password", password)
                .addParams("IS_JSON", "true")
                .addParams("loginModel", "mobile")
                .addParams("VALUE_OBJES_4_JSON", "loginUser")
                .addParams("userLoginModel", "mobile")
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
         return result;
    }


//postString【Json数据】请求
public String postJsonApi(PostJsonModel postJsonModel, StringCallback callback){
        String result = "";
        OkHttpUtils
                .postString()
                .url(getSpcyUrl(ServerApi.POSTJSON_URL))
                .content(new Gson().toJson(postJsonModel))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

//post提交文件请求
public String postFileApi(File file, StringCallback callback){
        String result = "";
        OkHttpUtils
                .postFile()
                .url(getSpcyUrl(ServerApi.POSTFILE_URL))
                .file(file)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

*/

RegisterActivity 调用封装好的请求

package com.example.administrator.myokhttp.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.myokhttp.MainActivity;
import com.example.administrator.myokhttp.MyApplication;
import com.example.administrator.myokhttp.R;
import com.example.administrator.myokhttp.ServerApi;
import com.example.administrator.myokhttp.UserNet;
import com.example.administrator.myokhttp.httputil.NetCallBackImp;
import com.example.administrator.myokhttp.httputil.NetUtil;
import com.example.administrator.myokhttp.utils.PrefManager;
import com.example.administrator.myokhttp.utils.ToastUtil;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class RegisterActivity extends Activity implements View.OnClickListener {

    private EditText mMsmCode, mImageCode, vPhoneTv;
    private TextView mRegisterBt, vSmsTimeTv, vSend;
    private LinearLayout vSmsTimeLin;
    private ImageView tvYzm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        initView();
        initEvent();
        initData();
    }

    protected void initView() {

        tvYzm = (ImageView) findViewById(R.id.tvYzm);
        mMsmCode = (EditText) findViewById(R.id.mMsmCode);
        mImageCode = (EditText) findViewById(R.id.mImageCode);
        vPhoneTv = (EditText) findViewById(R.id.vPhoneTv);
        mRegisterBt = (TextView) findViewById(R.id.mRegisterBt);
        vSend = (TextView) findViewById(R.id.tvSend);
    }

    protected void initEvent() {
        vSend.setOnClickListener(this);
        mRegisterBt.setOnClickListener(this);


        tvYzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImageCode();
            }
        });
    }

    protected void initData() {
        getImageCode();
    }

    private void getImageCode() {
        if (NetUtil.isNetworkAvailable(this)) {
            //执行网络请求接口
            try {
                UserNet.Instance().imageCode(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(Bitmap response, int id) {
                        Log.d("======sss", response.toString());
                        tvYzm.setImageBitmap(response);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.show(RegisterActivity.this, MyApplication.getAppContext().getResources().getString(R.string.network_enable));
        }
    }

    private void mobileCode() {
        if (NetUtil.isNetworkAvailable(this)) {
            //执行网络请求接口
            try {
                UserNet.Instance().mobileCode(vPhoneTv.getText().toString(), mImageCode.getText().toString(), new NetCallBackImp() {
                    @Override
                    public void pareOk(JSONObject data) {
                        super.pareOk(data);
                    }

                    @Override
                    public void paresOther(String code, String message) {
                        super.paresOther(code, message);
                    }

                    @Override
                    public void requestFinish() {
                        super.requestFinish();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.show(RegisterActivity.this, MyApplication.getAppContext().getResources().getString(R.string.network_enable));
        }
    }

    private void app_login() {
        if (NetUtil.isNetworkAvailable(this)) {
            //执行网络请求接口
            try {
                UserNet.Instance().app_login(vPhoneTv.getText().toString(), mMsmCode.getText().toString(), new NetCallBackImp() {

                    @Override
                    public void pareOk(JSONObject data) {
                        super.pareOk(data);
                        Log.d("======sss", data.toString());

                        try {

                            if (data.has("token")) {
                                PrefManager.getInstance().setString(ServerApi.SP_TOKEN, data.getString("token"));
                                Log.d("=====token", data.getString("token"));
                            }
                            ToastUtil.show(RegisterActivity.this, "登录成功!");
                            Intent intent = new Intent(RegisterActivity.this, MainActivityNew.class);
                            startActivity(intent);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void paresOther(String code, String message) {
                        super.paresOther(code, message);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.show(RegisterActivity.this, MyApplication.getAppContext().getResources().getString(R.string.network_enable));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mRegisterBt:
                app_login();
                break;
            case R.id.tvSend:
                mobileCode();
                break;
        }
    }
}

可以对请求回调进行进一步的封装


public class NetCallBackImp extends StringCallback {

    @Override
    public void onError(Call call, Exception error, int id) {
        requestFinish();
        Log.e("Net:", error.getMessage() + "||||||||" + error.getCause());
        paresError("no", "网络或服务器异常,请稍后再试!");
    }

    @Override
    public void onResponse(String st, int id) {
        String statusCode = "";
        try {
            JSONObject response = new JSONObject(st) ;

            Log.d("=====tttt",response.toString());

            requestFinish();
            pareOkAll (response) ;

            if (response.has("code")) {
                statusCode = response.getString("code");
                pareOkCode(statusCode, response);


                if ("SUCCESS".equals(statusCode)) {
                    pareOk(response);
                    JSONObject data = null;
                    if (response.has("data")) {
                        data = response.getJSONObject("data");
                        pareOkData(data);
                    }

                } else if ("NOT_LOGIN".equals(statusCode)) {
//                    EventBus.getDefault().post(new UserEvent(UserEvent.LOGIN_TOLOGIN));
                }  else  {
                    Log.d("====sss",response.getString("msg"));
                    if (response.has("msg")) {
                        paresOther(statusCode, response.getString("msg"));
                    } else {
                        paresOther(statusCode, "服务器异常,请稍后再试!!");
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            paresError("no", "服务器异常,请稍后再试!");
        }
    }

    public void requestFinish() {

    }
    public void pareOkAll( JSONObject response) {
    }
    public void pareOkCode(String  statusCode, JSONObject response) {
    }
    public void pareOk(JSONObject data) {
    }

    public void pareOkData(JSONObject data) {
    }
    public void paresOther(String  code, String message) {

        Log.d("====message",message);
        ToastUtil.show(MyApplication.getAppContext(), message);
   /*     if (code == 0) {
//            EventBus.getDefault().post(new UserEvent(UserEvent.LOGIN_AUTOLOGIN));
            return;
        }
        if (code == 10008 || code == 10007) {  //|| code == 10006
            EventBus.getDefault().post(new UserEvent(UserEvent.LOGIN_TOLOGIN));
            return;
        }*/

    }

    public void paresError(String code, String message) {
        ToastUtil.show(MyApplication.getAppContext(), message);
        paresOther(code, message);
    }



}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值