网络请求框架----okhttp3

一、okhttp3的使用1、添加依赖compile 'com.squareup.okhttp3:okhttp:3.7.0'compile 'com.squareup.okio:okio:1.12.0'2、基本用法 (1)get异步请求 private void get(String url){ OkHttpClient client = ne...
摘要由CSDN通过智能技术生成

一、okhttp3的使用

1、添加依赖

compile 'com.squareup.okhttp3:okhttp:3.7.0'
compile 'com.squareup.okio:okio:1.12.0'

2、基本用法

    (1)get异步请求

    private void  get(String url){
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url(url)
                .header("","")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }
        });
    }

(2)post异步请求(参数为Map)

    private void post(String url, Map<String, String> maps) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        if (maps == null) {
            maps = new HashMap<>();
        }
        Request.Builder builder = new Request.Builder()
                .url(url);
        if (maps != null && maps.size() > 0) {
            FormBody formBody = new FormBody.Builder();
            for (String key : maps.keySet()) {
                body.add(key, paramsMap.get(key));
            }
            builder.post(formBody.builder());
        }
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }
        });
    }

(3)post异步请求(参数为json)

private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");   
public void post(String url,JsonObject json) {
        
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url("")
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            }
        });
    }

(4)上传文件  MutipartBody

 private void  postFile(){
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        RequestBody requestBody = 
  RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8") , new File(""));
        String name = "fileName";          //文件名称
        try {
            name = URLEncoder.encode(name, "UTF-8");                 //文件名称编码,防止出现中文乱码
        } catch (UnsupportedEncodingException e1) {
            //TODO
        }

        //定义请求体,前面三个为表单中的string类型参数,第四个为需要上传的文件
        MultipartBody mBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("fileSize" , "12123")
                .addFormDataPart("time" , "234234")
                .addFormDataPart("name" , name)
                .addFormDataPart("file" , name , requestBody)
                .build();
        
        Request request = new Request.Builder().url("").header("","").post(mBody).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }
        });
    }

3、异步请求结果

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

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //结果在工作线程中,不能直接更新UI
                //如果希望返回的是字符串
                final String responseData=response.body().string();
                //如果希望返回的是二进制字节数组
                byte[] responseBytes=response.body().bytes();
                //如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
                InputStream responseStream=response.body().byteStream();
 
            }
        });

注: 异步请求callback回调是在工作线程中,所以不能直接更新UI,可以通过Looper.myLooper()==Looper.getMainLooper()   进行简单判断,解决方式可以使用Handler

 

4、Request的参数RequestBody

    RequestBody是抽象类,FormBody和MultipartBody是其子类。

Request request = new Request.Builder()
                            .url("")
                            .header("", "")
                            .post(RequestBody   body)
                            .build();

 

//RequestBody的创建
RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8") , new File(""));
或
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody imgBody = MultipartBody.create(MEDIA_TYPE_PNG, new Flie());

//FormBody的创建
FormBody body = new FormBody.Builder()
                .add("", "")
                .build();

//MultipartBody的创建
MultipartBody body=new MultipartBody.Builder()
                .addFormDataPart("key","value")
                .addFormDataPart("name","fileName",RequestBody body)
                .build();

5、自定义拦截器

(1)日志拦截器

public class LogInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        Headers headers = request.headers();
        Set<String> names = headers.names();
        Iterator<String> iterator = names.iterator();
        //打印请求路径
        Log.d(getClass().getSimpleName(), "url=" + request.url());
        //打印header
        Log.d(getClass().getSimpleName(), "=======headers   start=====");
        while (iterator.hasNext()) {
            String next = iterator.next();
            Log.d(getClass().getSimpleName(), next + ":" + headers.get(next));
        }
        Log.d(getClass().getSimpleName(), "=======headers   end=====");

        //打印post方式请求参数
        String method = request.method();
        if (method.equals("POST")) {
            RequestBody body = request.body();
            if (body != null) {
                if (body.contentType() != null) {
                    Log.d(getClass().getSimpleName(), "contentType:" + body.contentType().toString());
                }
                Log.d(getClass().getSimpleName(), "=======params   start=====");
                if (body instanceof FormBody) {
                    FormBody formBody = (FormBody) body;
                    for (int i = 0; i < formBody.size(); i++) {
                        Log.d(getClass().getSimpleName(), formBody.name(i) + ":" + formBody.value(i));
                    }
                }
                Log.d(getClass().getSimpleName(), "=======params   end=====");
            }

        }

        //打印response
        Response response = chain.proceed(request);
        ResponseBody body = response.body();
        if (body != null) {
            Log.d(getClass().getSimpleName(), "response:" + body.toString());
        }
        return response;
    }
}

(2)添加header拦截器

/*
 * 添加请求头
 */
public class HeadInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader("key", "value")
                .build();
        Headers headers = request.headers();
        Set<String> names = headers.names();
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Log.d("aaa", next + ":" + headers.get(next));
        }
        Response response = chain.proceed(request);

        return 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值