Android 网络框架之okhttp源码解析

okhttp使用

okhttp则分为Request请求与response响应。

request请求体:每一个HTTP请求中都应该包含一个URL,一个GET或POST方法以及Header或其他参数,当然还可以含特定内容类型的数据流。

response 响应码:响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body。

封装的okhttp库与okhttp使用:

blog.csdn.net/xjz123456qq…

基本请求(GET POST)

GET

Request.Builder builder = new Request.Builder();
        Request request = builder.get().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException error) {
               //响应失败
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //响应成功
            }
        });

POST

RequestBody body = RequestBody.create(JSON, jsonObject.toString());
 client.newCall(
                new Request.Builder()
                        .url(url)
                        //      .headers()//添加头
                        .post(body)
                        .build()).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOExce

你可能感兴趣的:(移动开发,Android,开源框架,android,kotlin,开发语言,移动开发,网络框架)