OkHttp的介绍及基础使用

特点

    开源Http库
    支持GZIP压缩
    支持响应缓存
    支持链接复用
    Okhttp作为安卓4.4的UrlConnection的底层采纳

配置

    compile 'com.squareup.okhttp3:okhttp:3.4.1'

配置OkhttpClient

//单独配置一个使用newBuilder()
    private OkHttpClient mHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS).build();

get请求

    private String doGet() {
        Request request = new Request.Builder().url("http://httpbin.org/get")
                .header("User-Agent", "OkHttpDemo/1.0")//同一个key,覆盖
                .header("User-Agent", "OkHttpDemo/2.0")
                .addHeader("X-Key", "value1")
                .addHeader("X-Key", "value2").build();//同一个key,追加
        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

post请求

    private String doPost() {
        //请求体
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/plain");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                InputStream inputStream = getResources().openRawResource(R.raw.data);
                byte[] buffer = new byte[1024];
                int read;
                while ((read = inputStream.read(buffer)) > 0) {
                    sink.write(buffer, 0, read);
                }
                sink.flush();
                inputStream.close();
            }
        };

        MultipartBody multipartBody = new MultipartBody.Builder().addPart(requestBody)
                .addPart(RequestBody.create(MediaType.parse("text/plain"),
                        "this is test data from code")).build();
        Request request = new Request.Builder().url("http://httpbin.org/post")
                .header("User-Agent", "OkHttpDemo/1.0")
                .method("POST", multipartBody)
                .build();
        try {
            Call call = mHttpClient.newCall(request);
            Response response = call.execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

异步get请求

    private void doGetAsync() {
        Request request = new Request.Builder().url("http://httpbin.org/get")
                .header("User-Agent", "OkHttpDemo/1.0").build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String result = response.body().string();
                    mTvContent.post(new Runnable() {
                        @Override
                        public void run() {
                            mTvContent.setText(result);
                        }
                    });
                }
            }
        });
    }
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34203494/article/details/53997806
个人分类: IO与线程
想对作者说点什么? 我来说一句

OkHttp库以及使用demo

2016年09月12日 3.47MB 下载

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

不良信息举报

OkHttp的介绍及基础使用

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭