关于OkGo中由于响应码不同返回的错误提示无法获取解决方案

   使用okgo过程中发现原有的callBack无法再onError方法中返回错误信息内容,所以可以通过自定义callBack 方法来获取响应的内容:

 eg:

 
  
package com.lide.mygit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button mBt_req;
    private TextView mTv_rece;
    private String mRequestJsonData;
    private String mPostUrl1;
    private String mPostUrl;
    private String mRequestJsonData1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBt_req = (Button) findViewById(R.id.bt_req);
        mTv_rece = (TextView) findViewById(R.id.tv_receive);
        mBt_req.setOnClickListener(this);
       init();
    }

    private void init() {

        String apiMethod = "api/seeding-position/wave-number/confirm";
        mPostUrl = Configs.apiUrl + apiMethod;

        RequestLookProduct requestLookProduct = new RequestLookProduct();
        requestLookProduct.waveNumber = "222";

        mRequestJsonData1 = new Gson().toJson(requestLookProduct);

    }


    @Override
    public void onClick(View v) {
        OkGo.post(mPostUrl).tag(this).upJson(mRequestJsonData1).headers("authorization", "APP_KEYS "+Configs.appKey).execute(new MyCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                Toast.makeText(MainActivity.this,"before",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                mTv_rece.setText(s);
                Log.d("test",s);
            }

            @Override
            public void MyOnError(Call call, Response response, Exception e,String errorMsg) {
                  mTv_rece.setText(errorMsg);
                 Toast.makeText(MainActivity.this,"error"+e.getMessage()+"__"+errorMsg,Toast.LENGTH_SHORT).show();

        }

        });


    }


    public  abstract  class MyCallback extends AbsCallback {

        private String mS;

        @Override
        public  abstract void onSuccess(String s, Call call, Response response) ;

        @Override
        public String convertSuccess(Response response) throws Exception {
            mS = StringConvert.create().convertSuccess(response);

            response.close();
            return mS;
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            MyOnError(call, response, e,mS);
        }
        
        public abstract void MyOnError(Call call, Response response, Exception e,String errorMsg) ;
    }

   
}

你可能感兴趣的:(关于OkGo中由于响应码不同返回的错误提示无法获取解决方案)