OkHttp简单封装

使用链式编程思想封装网络请求客户端

            public class SimpleHttpClient {
private Builder mBuilder;
//构造传递Builder对象
private SimpleHttpClient(Builder builder) {
    mBuilder=builder;
}
//构建builderRequest
public Request buildRequest(){
    Request.Builder builder=new Request.Builder();
    if(mBuilder.method=="GET"){
        builder.url(buildGetRequestParam());
        builder.get();
    }else if(mBuilder.method=="POST"){
        builder.post(buildRequestBody());
        builder.url(mBuilder.url);
    }
    return builder.build();
}
//构建builderRequestBody
private RequestBody buildRequestBody()  {
    if(mBuilder.isJsonParam){
        JSONObject jsonObject=new JSONObject();
        for(RequestParam p:mBuilder.mParams){
            try {
                jsonObject.put(p.getKey(),p.getObj());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String json = jsonObject.toString();
        Log.d("SimpleRequest","Request json="+json);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
    }
    FormBody.Builder builder=new FormBody.Builder();
    for(RequestParam p:mBuilder.mParams){
        builder.add(p.getKey(),p.getObj()==null?"":p.getObj().toString());
    }
    return builder.build();
}
//供外部请求调用,实现网络请求
public void enqueue(BaseCallBack callBack){
    OkHttpManager.getmInstance().request(this,callBack);
}
//链式编程封装Builder对象提供给外部
public static Builder newBuilder(){
    return new Builder();
}
//参数构建方法供调用
private String buildGetRequestParam(){
    if(mBuilder.mParams.size()<=0){
        return this.mBuilder.url;
    }
    Uri.Builder builder=Uri.parse(mBuilder.url).buildUpon();
    for(RequestParam p:mBuilder.mParams){
        builder.appendQueryParameter(p.getKey(),p.getObj()==null?"":p.getObj().toString());
    }
    String url=builder.build().toString();
    Log.d("SimpleRequest","the get url="+url);
    return url;
}
//builder对象内部类
public static class Builder{
    private String url;
    private String method;
    private boolean isJsonParam;
    private List mParams;
    private Builder(){
        method="GET";
    }
    public SimpleHttpClient builder(){
        return new SimpleHttpClient(this);
    }
    public Builder url(String url){
        this.url=url;
        return this;
    }
    public Builder get(){
        method="GET";
        return this;
    }
    public Builder post(){
        method="POST";
        return this;
    }
    public Builder json(){
        isJsonParam=true;
        return post();
    }
    public Builder addParam(String key,Object value){
        if(mParams==null){
            mParams=new ArrayList<>();
        }
        mParams.add(new RequestParam(key,value));
        return  this;
    }
}

}

OkHttp初始化设置,请求返回处理

          public class OkHttpManager {
private static OkHttpManager mInstance;
private OkHttpClient mOkHttpClient;
private Handler mHandler;
private Gson mGson;
private OkHttpManager() {
    initOkHttp();
    mHandler=new Handler();
    mGson=new Gson();
}
public static synchronized OkHttpManager getmInstance(){
    if(mInstance==null){
        mInstance=new OkHttpManager();
    }
    return mInstance;
}
private void initOkHttp(){
    mOkHttpClient=new OkHttpClient().newBuilder().readTimeout(30000, TimeUnit.SECONDS)
            .connectTimeout(30000,TimeUnit.SECONDS).build();
}
public void request(SimpleHttpClient client, final BaseCallBack 
  callBack){
    if(callBack==null){
        throw new NullPointerException("callback is null");
    }
    mOkHttpClient.newCall(client.buildRequest()).enqueue(new                   
  Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

// callBack.onFailure(call,e);
sendonFailureMessage(callBack,call,e);
}

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){
                  String result=response.body().string();
                  if(callBack.mType==null||callBack.mType==String.class){
                      sendonSuccessMessage(callBack,result);
                  }else {
                    sendonSuccessMessage(callBack,mGson.fromJson(result,callBack.mType));
                  }
                  if(response.body()!=null){
                      response.body().close();
                  }
            }else {
                sendonErrorMessage(callBack,response.code());
            }
        }
    });
}
private void sendonFailureMessage(final BaseCallBack callBack, final Call call, final IOException e){
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            callBack.onFailure(call,e);
        }
    });
}
private void sendonErrorMessage(final BaseCallBack callBack, final int code){
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            callBack.onError(code);
        }
    });
}
private void sendonSuccessMessage(final BaseCallBack callBack, final Object value){
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            callBack.onSuccess(value);
        }
    });
}
}

调用封装的网络请求

                        String url=Config.API.BASE_URL+"login/json";
    SimpleHttpClient.newBuilder().addParam("username",username).addParam("password",password).json().url(url)
            .builder().enqueue(new BaseCallBack() {
        @Override
        public void onSuccess(BaseResult baseResult) {
            super.onSuccess(baseResult);
            Toast.makeText(LoginActivity2.this, "封装请求"+baseResult.getMessage(), Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onError(int code) {
            super.onError(code);
            Toast.makeText(LoginActivity2.this, "封装请求--"+code, Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            Toast.makeText(LoginActivity2.this, "封装请求"+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

你可能感兴趣的:(OkHttp简单封装)