美文网首页
Okhttp的基础使用

Okhttp的基础使用

作者: BillyJean | 来源:发表于2022-03-21 11:56 被阅读0次

    1.添加依赖:

     implementation("com.squareup.okhttp3:okhttp:4.9.0")
    

    2.配置请求:

    • 2.1 GET请求:
    • GET 同步请求:
     //同步请求,请求时没回应,会阻塞
        public void getSync(View view) {
        OkHttpClient okHttpClient = new OkHttpClient();
            //网络请求必须在子线程执行
            new Thread(){
                @Override
                public void run() {
                    //Request代表请求对象,会将域名,请求地址,参数封装
                    //若是要在get后面直接加参数格式是在get后面加:?a=1&b=2
                    Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
                    //准备好请求的Call对象
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response response = call.execute();
                        Log.i(TAG, "getSync: "+response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    
    • GET异步请求:
     public void getAsync(View view) {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
            //准备好请求的Call对象
            Call call = okHttpClient.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 {
               //响应码 200~299成功,400~500服务器错误,跟服务器的通信是成功的都会回调这个函数,但是服务器处理请求的数据不一定成功
                    if (response.isSuccessful()){
                        Log.i(TAG, "getAsync: "+response.body().string());
                    }
                }
            });
        }
    
    • 2.2 POST请求:
    • POST同步请求:
       public void postSync(View view) {
            OkHttpClient okHttpClient = new OkHttpClient();
            //okhttp创建的request对象默认是get请求,如果是post要使用FormBody配合.post()设置
            //而POST请求要设置RequestBody
            new Thread(){
                @Override
                public void run() {
                    FormBody formBody = new FormBody.Builder()
                            .add("a", "1")
                            .add("b", "2")
                            .build();
                    Request request = new Request.Builder()
                            .url("https://www.httpbin.org/post")
                            .post(formBody)
                            .build();
                    //准备好请求的Call对象
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response response = call.execute();
                        Log.i(TAG, "PostSync: "+response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }.start();
        }
    
    • POST异步请求:
     public void postAsync(View view) {
            OkHttpClient okHttpClient = new OkHttpClient();
            FormBody formBody = new FormBody.Builder()
                    .add("a", "1")
                    .add("b", "2")
                    .build();
            Request request = new Request.Builder()
                    .url("https://www.httpbin.org/post")
                    .post(formBody)
                    .build();
            //准备好请求的Call对象
            Call call = okHttpClient.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 {
                    if (response.isSuccessful()){
                        Log.i(TAG, "PostAsync: "+response.body().string());
                    }
                }
            });
        }
    

    两者综合来看,request对应的是get请求,而formbody对应的是post请求

    3.添加拦截器:

     public void interceptorTest(){
            //addInterceptor一定在前面执行,addNetworkInterceptor一定在后面执行
            //使用cache缓存
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    //开启缓存
                    .cache(new Cache(new File("C:\\Users\\Administrator\\Desktop\\cache"),1024*1024))
                    .addInterceptor(new Interceptor() {
                @NotNull
                @Override
                public Response intercept(@NotNull Chain chain) throws IOException {
                    //请求之前的前置处理,和请求之后的后置处理
                    //例如请求前,添加平台,版本号
                    //在请求前可以拿到这个request对象,再重新封装一个新的request,把平台信息和版本号封装进去,再发出去
                    //拦截器可以添加多个,按照顺序来执行
                    Request request = chain.request().newBuilder().addHeader("os", "android").addHeader("version", "1.1.0").build();
                    Response response = chain.proceed(request);
                    return response;
                }
            }).addNetworkInterceptor(new Interceptor() {
                @NotNull
                @Override
                public Response intercept(@NotNull Chain chain) throws IOException {
                    System.out.println("version:"+chain.request().header("version"));
                    return chain.proceed(chain.request());
                }
            }).build();
    
            Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    4.文件上传:

    public void uploadFileTest(){
            //上传的是:文件的key,文件的名字,文件本身
            //采用的是MultipartBody来封装
            //MediaType详情参考:https://blog.csdn.net/sinat_34241861/article/details/110648469
            //Content_Type:application/x-www-form-urlencoded 默认是这种提交,采取的形式是键值对形式:key1:value1&key2:value2&key3:value3
            //Content_type:multipart/form-data,数据被编码为一条消息,一般用于文件上传
            //Content_Type:application/octet-stream,提交二进制数据,如果用于文件上传,只能上传一个文件
            //Content_Type:application/json,提交json数据
           OkHttpClient okHttpClient = new OkHttpClient();
            File file1 = new File("C:\\Users\\Administrator\\Desktop\\1.txt");
            File file2 = new File("C:\\Users\\Administrator\\Desktop\\2.txt");
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .addFormDataPart("file1", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
                    .addFormDataPart("file2", file2.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
                    .addFormDataPart("a","1")//还可以添加额外的参数
                    .build();
            Request request = new Request.Builder().url("https://www.httpbin.org/post").post(multipartBody).build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    5.Json数据上传:

             //上传json数据
            //使用的RequestBody来封装
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", MediaType.parse("application/json"));
            Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    .使用cookies:

    cookie是某些网站为了辨别用户的身份,进行会话跟踪(比如确定登录状态)而存储在本地终端上的数据,由客户端保存信息

    public class UseCookie {
        //cookie的相关配置
        Map<String,List<Cookie>> cookies = new HashMap<>();
        @Test
        public void useCookie(){
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .cookieJar(new CookieJar() {
                        @Override
                        public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
                            //会把服务器返回的cookie封装成list集合,返回回来,可以用文件保存或者放在内存中
                            cookies.put(httpUrl.host(),list);
                        }
                        @NotNull
                        @Override
                        public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                            //请求网站的url
                          List<Cookie> cookies = UseCookie.this.cookies.get(httpUrl.host());
                          return cookies == null ? new ArrayList<Cookie>():cookies;
                        }
                    })
                    .build();
           //填入你自己的wanandroid账号和密码
            FormBody formBody = new FormBody.Builder().add("username", "xxx")
                    .add("password", "xxxxxx").build();
            Request request = new Request.Builder().url("https://www.wanandroid.com/user/login")
                    .post(formBody)
                    .build();
            //准备好请求的Call对象
            Call call = okHttpClient.newCall(request);
            //进行同步请求
            try {
                Response response = call.execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            //请求收藏文章列表接口
            request = new Request.Builder().url("https://www.wanandroid.com/lg/collect/list/0/json")
                    .build();
            //准备好请求的Call对象
            call = okHttpClient.newCall(request);
            //进行同步请求
            try {
                Response response = call.execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:Okhttp的基础使用

          本文链接:https://www.haomeiwen.com/subject/ncozdrtx.html