okhttp 2.x 用法/封装

okhttp 2.x 用法/封装

android的网络框架okhttp被普遍使用,包括现在比较强大的retrofit也是封装okhttp 简单了解okhttp(get/post):
//get请求:

  private void getRequest() {
    //创建okHttpClient对象
    OkHttpClient mOkHttpClient = new OkHttpClient();
    final Request request = new Request.Builder()
            .url("http://www.baidu.com")
            .build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
        }
        @Override
        public void onResponse(final Response response) 
        throws IOException {
        //异步请求 更新UI需要切到主线程
                }
            });
        }
    });
}

//post请求

private void postAsynHttp() {
    OkHttpClient mOkHttpClient = new OkHttpClient();
    //设置post请求数据
    RequestBody formBody = new FormEncodingBuilder()
            .add("size", "10")
            .build();
    Request request = new Request.Builder()
            .url("http://blog.youkuaiyun.com/soullines/article/details/78040109")
            .post(formBody)
            .build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
        }
        @Override
        public void onResponse(Response response) 
        throws IOException {
            });
        }
    });
}

当然okhttp的使用需要封装 —->当然okhttp可以设置请求超时和设置缓冲

public class OkHttpEngine {
    private static OkHttpEngine mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;
    //单例模式
    public static OkHttpEngine getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpEngine.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpEngine();
                }
            }
        }
        return mInstance;
    }
    //设置超时
    private setTimeout() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(20, TimeUnit.SECONDS);
        mHandler = new Handler();
    }

    //设置缓冲
    public void setCache(Context mContext) {
        File sdcache = mContext.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        mOkHttpClient.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
    }
    /**
     * 异步get请求
     * @param url
     * @param callback
     */
    public void getAsynHttp(String url, ResultCallback callback) {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        dealResult(call, callback);
    }
    private void dealResult(Call call, final ResultCallback callback) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                sendFailedCallback(request, e, callback);
            }
            @Override
            public void onResponse(final Response response) throws IOException {
                sendSuccessCallback(response, callback);
            }
            private void sendSuccessCallback(final Response objec
            t, final ResultCallback callback) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onResponse(object);
                        }
                    }
                });
            }
            private void sendFailedCallback(final Request 
            request, final Exception e, final ResultCallback 
            callback) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onError(request, e);
                    }
                });
            }
        });
    }
}

//okhttp封装之后的使用

    OkHttpEngine.getInstance()
        .setTimeout()//可以修改封装代码 动态设置请求超时时间
        .setCache(this)
        .getAsynHttp("http://www.baidu.com", new ResultCallback() {
          @Override
          public void onError(Request request, Exception e) {
          }

          @Override
          public void onResponse(Response response) {
          }
      });

简单的okhttp封装,android中可定制使用

数:....oe.ex.m X sExecutionException: [ERR-TMS-998]java.net.SocketExc eption: Socket closed at java.net.SocketInputStream.rea d(SocketInputStream.java: 204) at java.net.SocketInputS tream.read(SocketInputStream.java: 141) at okio.Okio$2. read(Okio.java: 140) at okio.AsyncTimeout$2.read(AsyncTimeout.jav a: 237) at okio.RealBufferedSource.indexOf(RealBufferedSource.java: 355) at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSour ce.java: 227) at okhttp3.internal.http1.Http1Codec.readHeaderLine(Ht tp1Codec.java: 215) at okhttp3.internal.http1.Http1Codec.readRespon seHeaders(Http1Codec.java: 189) at okhttp3.internal.http.CallServerI nterceptor.intercept(CallServerInterceptor.java: 88) at okhttp3.interna Lhttp.RealInterceptorChain.proceed(RealInterceptorChain.java: 147) at okhttp3.intemal.connection.ConnectInterceptor.intercept(ConnectI nterceptor.java: 45) at okhttp3.internal.http.RealInterceptorChain.pro ceed(RealinterceptorChain.java: 147) at okhttp3.Internal.http,RealInt erceptorChain.proceed(RealInterceptorChain. java: 121) at okhttp3.int ernal.cache.Cathetnterceptor intercept(Cachelrterceptor. java:93)at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorC hain.java: 147) at okhttp3.intemal.http.RealinterceptorChain.proceed (ReallnterceptorChain.java: 121) at okhttp3. internal.http.BrdgeInterc eptor intercept(BridgeInterceptor.java: 93) at okhttp3.internalhttp.Re alinterceptorChain.proceed(RealInterceptorChain. java: 147) at okhttp 3. internalhttp.RetryAndFollowUpInterceptor. intercept(RetryAndFollo wUpInterceptor.java: 126) at okhttp3.internal.http.RealnterceptorCh an.proceed(ReallnterceptorChain.java: 147) at okhttp3.internalhttp. erod(tetoh va:121)at k RClsreChi(ealallva:200)at p caent u-tto 3ClentitpReque executeinterna ctn Chenes
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值