OKhttp3 简单使用,文件 表单post请求

Okhttp框架简单使用(这里只举例enqueue  post请求),本篇是基本的使用和认识都是非常简单的代码注释写的很清楚就不多废话了直接看代码片段吧!

GET请求

public void getRequest(){
    try {
        //构建request
        Request request = new Request.Builder().url(url).get().build();
        //尝试添加拦截器
        OkHttpClient.Builder clientBuilder = client.newBuilder();
        //添加一个log拦截器
        client =clientBuilder.addInterceptor(new HttpLoggingInterceptor()
               .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            publicvoid onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            publicvoid onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    } catch(Exception e) {
        e.printStackTrace();
    }
}

POST请求(只有form参数的亲求)

public void postRequest() {
    try {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        builder.addEncoded("key1","1");
        builder.addEncoded("key2","2");
        ...
        //去构建
        FormBody formBody = builder.build();
        //去请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        //尝试添加拦截器
        OkHttpClient.Builder clientBuilder = client.newBuilder();
        //添加一个log拦截器
        client = clientBuilder.addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

文件/表单混合提交


/**
 * 混合form和图片
 */
public void postMultipartReauest(String url, Map params, List files) {
    try {
        //构建多部件builder
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.ALTERNATIVE);
        //两种添加数据的方式,二选一
        //- - - - - - - - - - - - - -第一种(不推荐)- - - - - - - - - - - - - -
        FormBody.Builder builder = new FormBody.Builder();
        if (params!=null) {
            for (String key1 : params.keySet()) {
                builder.addEncoded(key1, params.get(key1));
            }
        }
        //添加参数
        bodyBuilder .addPart(Headers.of(
                "Content-Disposition",
                "form-data; name=\"params\"")
                ,builder.build());
   
        //添加图片
        if (files!=null) {
            for (File f1 : files) {
                RequestBody fileBody=RequestBody.create(MediaType.parse("aimage/png"),f1);
                bodyBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imagetype\"")
                        , fileBody);
            }
        }
        //- - - - - - - - - - - - - -第二种(推荐)- - - - - - - - - - - - - -
        //获取参数并放到请求体中
        if (params!=null) {
            for (String key2 : params.keySet()) {
                bodyBuilder.addFormDataPart(key2, params.get(key2));
            }
        }
        //添加图片集合
        if (files!=null) {
            for (File f2 : files) {
                bodyBuilder.addFormDataPart("pic", f2.getName(), RequestBody.create(MediaType.parse("image/png"), f2));
            }
        }
        //去请求
        Request request = new Request.Builder()
                .url(url)
                .post(bodyBuilder.build())
                .build();
        //尝试添加拦截器
        OkHttpClient.Builder clientBuilder = client.newBuilder();
        //添加一个log拦截器
        client = clientBuilder.addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

简单分析

Okhttp 在应用上说,分四步 :
一、 构建OkHttpClient 
二、 构建Request 
三、 通过newCall建立请求call,内部分裝了enqueue同步(不会使用线程池),对应的Call实现类RealCall,enqueue异步(使用线程池)
对应的Call实现类AsyncCall 
四、 通过Callback(其实是回调到我们外部实现匿名实现类处理结果)

后续按照使用的方式逐步分析源码、构架、封装使用-----坚持就是胜利~!!

    最后如果有错误或者理解不对的地方可评论或者私信给我~~多谢

你可能感兴趣的:(okhttp3,学习之路)