Retrofit的使用

1、github网址:GitHub - square/retrofit: A type-safe HTTP client for Android and the JVM

依赖:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

2、使用方法

2.1、创建retrofit

Retrofit retrofit = RetrofitCreate.getRetrofit();
public class RetrofitCreate {
    private volatile static Retrofit sRetrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Constants.BASE_URL)
            .build();

    public static Retrofit getRetrofit() {
        return sRetrofit;
    }
}

2.2、创建api

public interface API {
    // get请求
    @GET("/get/text")
    Call<JsonResult> getJson();

    // get请求-@Query注解带参数的get请求
    @GET("/get/param")
    Call<GetResultByParamsJson> getResultByParamsJson(@Query("keyword") String keyword, @Query("page") int page,
                                                      @Query("order") String order);

    // get请求-@QueryMap注解-带参数的get请求
    @GET("/get/param")
    Call<GetResultByParamsJson> getResultByParamsJson(@QueryMap Map<String, Object> params);

    // get请求-@Url注解完成文件下载
    @GET
    Call<ResponseBody> getResultByFileUrl(@Url String url);

    // post请求-@Query注解带参数
    @POST("/post/string")
    Call<PostByParamsJson> postByParamsJson(@Query("string") String string);

    // post请求-@Url注解带参数
    @POST
    Call<PostByParamsJson> postByUrlJson(@Url String url);

    // post请求-使用@Body注解完成提交评论内容
    @POST("/post/comment")
    Call<PostByParamsJson> postCommentJson(@Body CommentContent commentContent);

    // post请求-使用@Part注解上传单个文件,注意要加@Multipart注解
    @Multipart
    @POST("/file/upload")
    Call<PostFileJson> postFile(@Part MultipartBody.Part part);

    // post请求-使用@Part注解上传多个文件,注意要加@Multipart注解
    @Multipart
    @POST("/files/upload")
    Call<PostFileJson> postFiles(@Part List<MultipartBody.Part> parts);

    // post请求-使用@Part注解上传文件 @QueryMap注解携带参数
    @Multipart
    @POST("/file/params/upload")
    Call<PostFileJson> postFileByParams(@Part MultipartBody.Part part, @QueryMap Map<String, String> params);

    // post请求-使用@Field注解实现登录,要加@FormUrlEncoded注解
    @FormUrlEncoded
    @POST("/login")
    Call<LoginJson> postLogin(@Field("userName") String userName, @Field("password") String password);

    // post请求-使用@FieldMap注解实现登录,要加@FormUrlEncoded注解
    @FormUrlEncoded
    @POST("/login")
    Call<LoginJson> postLoginByFieldMap(@FieldMap Map<String, String> fieldMap);
}

建立接口API,通过请求的参数对象构建bean类,通过注解的方式构建相应的方法

API api = retrofit.create(API.class);

通过retrofit.create(API.class)获取api

2.3、获取相应的方法并创建task

Call<JsonResult> task = api.getJson();

2.4、执行任务队列

task.enqueue(new Callback<JsonResult>() {
            @Override
            public void onResponse(Call<JsonResult> call, Response<JsonResult> response) {
                int responseCode = response.code();
                Log.d(TAG, "cfx responseCode " + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx getRequest 请求成功");
                    try {
                        // String resultStr = response.body().string();
                        // Log.d(TAG, "cfx " + resultStr);
                        // Gson gson = new Gson();
                        // JsonResult jsonResult = gson.fromJson(resultStr, JsonResult.class);
                        // updateUiList(jsonResult);

                        JsonResult jsonResult = response.body();
                        Log.d(TAG, "cfx jsonResult.toString() = " + jsonResult.toString());
                        updateUiList(jsonResult);
                    } catch (Exception e) {
                        Log.d(TAG, "cfx IOException: " + e);
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonResult> call, Throwable t) {
                // 请求失败
                Log.d(TAG, "cfx getRequest 失败 " + t);
            }
        });
    }

3、后续为其他注解的使用

// get带参数请求
    private void getResultByParams() {
        // 1.创建retrofit
        Retrofit retrofit = RetrofitCreate.getRetrofit();
        // 2.创建api
        API api = retrofit.create(API.class);
        // 3.创建任务
        Call<GetResultByParamsJson> resultByParamsJson = api.getResultByParamsJson("這是get帶參數请求", 6, "1");
        // 4.执行任务队列
        resultByParamsJson.enqueue(new Callback<GetResultByParamsJson>() {
            @Override
            public void onResponse(Call<GetResultByParamsJson> call, Response<GetResultByParamsJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 請求成功
                    Log.d(TAG, "cfx getResultByParams 请求成功");
                    GetResultByParamsJson getResultByParamsJson = response.body();
                    Log.d(TAG, "cfx getResultByParamsJson = " + getResultByParamsJson.toString());
                }
            }

            @Override
            public void onFailure(Call<GetResultByParamsJson> call, Throwable t) {
                // 请求失败
                Log.d(TAG, "cfx getResultByParams 请求失败 " + t);
            }
        });

    }

    // get带参数请求(使用QueryMap)
    private void getResultByParamsQueryMap() {
        // 1.创建retrofit
        Retrofit retrofit = RetrofitCreate.getRetrofit();
        // 2.创建api
        API api = retrofit.create(API.class);
        // 3.创建任务
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", "這是get帶參數请求QueryMap");
        params.put("page", 7);
        params.put("order", "0");
        Call<GetResultByParamsJson> resultByParamsJson = api.getResultByParamsJson(params);
        // 4.执行任务队列
        resultByParamsJson.enqueue(new Callback<GetResultByParamsJson>() {
            @Override
            public void onResponse(Call<GetResultByParamsJson> call, Response<GetResultByParamsJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 請求成功
                    Log.d(TAG, "cfx getResultByParamsQueryMap 请求成功");
                    GetResultByParamsJson getResultByParamsJson = response.body();
                    Log.d(TAG, "cfx getResultByParamsQueryMap = " + getResultByParamsJson.toString());
                }
            }

            @Override
            public void onFailure(Call<GetResultByParamsJson> call, Throwable t) {
                // 请求失败
                Log.d(TAG, "cfx getResultByParams 请求失败 " + t);
            }
        });

    }

    // get请求,@Url注解下载文件
    private void getResultByUrl() {
        String url = "/download/3";
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<ResponseBody> task = api.getResultByFileUrl(url);
        task.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    Log.d(TAG, "cfx getResultByUrl 请求成功 ");
                    Headers headers = response.headers();
                    // for (int i = 0; i < headers.size(); i++) {
                    //     String name = headers.name(i);
                    //     String value = headers.value(i);
                    //     Log.d(TAG, "cfx " + name + ": " + value);
                    // }

                    // 获取文件名
                    String stringHead = headers.get("Content-disposition");
                    Log.d(TAG, "cfx stringHead = " + stringHead);
                    String fileName = stringHead.replace("attachment; filename=", "");
                    Log.d(TAG, "cfx fileName = " + fileName);
                    String filePath = "/storage/self/primary/DCIM/Camera/" + fileName;
                    Log.d(TAG, "cfx filePath = " + filePath);
                    File file = new File(filePath);
                    // 当前线程在主线程,需要在子线程写文件(Thread.currentThread() = Thread[main,5,main])
                    Log.d(TAG, "cfx Thread.currentThread() = " + Thread.currentThread());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            InputStream inputStream = null;
                            FileOutputStream fileOutputStream = null;
                            try {
                                inputStream = response.body().byteStream();
                                fileOutputStream = new FileOutputStream(file);
                                int len = 0;
                                byte[] buffer = new byte[1024];
                                while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                                    fileOutputStream.write(buffer, 0, len);
                                }
                                fileOutputStream.flush();
                                Log.d(TAG, "cfx getResultByUrl run 下载文件成功");
                            } catch (Exception e) {
                                Log.d(TAG, "cfx getResultByUrl run Exception: " + e);
                            } finally {
                                if (fileOutputStream != null) {
                                    try {
                                        fileOutputStream.close();
                                    } catch (IOException e) {
                                        Log.d(TAG, "cfx getResultByUrl fileOutputStream IOException: " + e);
                                    }
                                }
                                if (inputStream != null) {
                                    try {
                                        inputStream.close();
                                    } catch (IOException e) {
                                        Log.d(TAG, "cfx getResultByUrl inputStream IOException: " + e);
                                    }
                                }
                            }
                        }
                    }).start();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "cfx getResultByUrl 请求失败 " + t);
            }
        });
    }

    // @POST注解带参数
    private void postResultByParams() {
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostByParamsJson> task = api.postByParamsJson("这是@POST注解带参数提交的字符串");
        task.enqueue(new Callback<PostByParamsJson>() {
            @Override
            public void onResponse(Call<PostByParamsJson> call, Response<PostByParamsJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByParams 请求成功");
                    PostByParamsJson postByParamsJson = response.body();
                    if (postByParamsJson != null) {
                        Log.d(TAG, "cfx postByParamsJson = " + postByParamsJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostByParamsJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByParams 请求失败 " + t);
            }
        });
    }

    // @URL注解带参数
    private void postResultByPUrl() {
        String url = "/post/string?string=这是使用@URL注解带参数提交的字符串";
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostByParamsJson> task = api.postByUrlJson(url);
        task.enqueue(new Callback<PostByParamsJson>() {
            @Override
            public void onResponse(Call<PostByParamsJson> call, Response<PostByParamsJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByPUrl 请求成功");
                    PostByParamsJson postByParamsJson = response.body();
                    if (postByParamsJson != null) {
                        Log.d(TAG, "cfx postResultByPUrl = " + postByParamsJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostByParamsJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByPUrl 请求失败 " + t);
            }
        });
    }

    // post请求@Body注解提交评论
    private void postResultByBody() {
        CommentContent commentContent = new CommentContent("123456", "这是post请求@Body注解提交评论");
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostByParamsJson> task = api.postCommentJson(commentContent);
        task.enqueue(new Callback<PostByParamsJson>() {
            @Override
            public void onResponse(Call<PostByParamsJson> call, Response<PostByParamsJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByBody 请求成功");
                    PostByParamsJson content = response.body();
                    if (content != null) {
                        Log.d(TAG, "cfx postResultByBody = " + content.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostByParamsJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByBody 请求失败 " + t);
            }
        });
    }

    // post请求@Part注解上传单个文件
    private void postResultByPartUploadFile() {
        MultipartBody.Part part = createMultipart("/storage/self/primary/DCIM/Camera/20191229_170919.jpg", "file");
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostFileJson> task = api.postFile(part);
        task.enqueue(new Callback<PostFileJson>() {
            @Override
            public void onResponse(Call<PostFileJson> call, Response<PostFileJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByPartUploadFile 请求成功");
                    PostFileJson postFileJson = response.body();
                    if (postFileJson != null) {
                        Log.d(TAG, "cfx postFileJson = " + postFileJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostFileJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByPartUploadFile 请求失败 " + t);
            }
        });
    }

    // post请求@Part注解上传多个文件
    private void postResultByPartUploadFiles() {
        List<MultipartBody.Part> parts = new ArrayList<>();
        parts.add(createMultipart("/storage/self/primary/DCIM/Camera/20200130_101202.jpg", "files"));
        parts.add(createMultipart("/storage/self/primary/DCIM/Camera/20200131_201856.jpg", "files"));
        parts.add(createMultipart("/storage/self/primary/DCIM/Camera/20200215_164424.jpg", "files"));
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostFileJson> task = api.postFiles(parts);
        task.enqueue(new Callback<PostFileJson>() {
            @Override
            public void onResponse(Call<PostFileJson> call, Response<PostFileJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByPartUploadFiles 请求成功");
                    PostFileJson postFileJson = response.body();
                    if (postFileJson != null) {
                        Log.d(TAG, "cfx postFileJsons = " + postFileJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostFileJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByPartUploadFiles 请求失败 " + t);
            }
        });
    }

    // post请求@Part注解携带参数上传文件
    private void postResultByParamsUploadFile() {
        Map<String, String> params = new HashMap<>();
        params.put("description", "这是post请求@Part注解携带参数上传文件");
        params.put("isFree", "false");
        MultipartBody.Part part = createMultipart("/storage/self/primary/DCIM/Camera/20200130_101202.jpg", "file");
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<PostFileJson> task = api.postFileByParams(part, params);
        task.enqueue(new Callback<PostFileJson>() {
            @Override
            public void onResponse(Call<PostFileJson> call, Response<PostFileJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx postResultByParamsUploadFile 请求成功");
                    PostFileJson postFileJson = response.body();
                    if (postFileJson != null) {
                        Log.d(TAG, "cfx postFileJson = " + postFileJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<PostFileJson> call, Throwable t) {
                Log.d(TAG, "cfx postResultByParamsUploadFile 请求失败 " + t);
            }
        });
    }

    // @Field注解实现登录
    private void fieldResultLogin() {
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<LoginJson> task = api.postLogin("cfx", "123456");
        task.enqueue(new Callback<LoginJson>() {
            @Override
            public void onResponse(Call<LoginJson> call, Response<LoginJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx fieldResultLogin 请求成功");
                    LoginJson loginJson = response.body();
                    if (loginJson != null) {
                        Log.d(TAG, "cfx LoginJson = " + loginJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginJson> call, Throwable t) {
                Log.d(TAG, "cfx fieldResultLogin 请求失败 " + t);
            }
        });
    }

    // @FieldMap注解实现登录
    private void fieldMapResultLogin() {
        Map<String, String> map = new HashMap<>();
        map.put("userName", "cfxcr");
        map.put("password", "111222333");
        API api = RetrofitCreate.getRetrofit().create(API.class);
        Call<LoginJson> task = api.postLoginByFieldMap(map);
        task.enqueue(new Callback<LoginJson>() {
            @Override
            public void onResponse(Call<LoginJson> call, Response<LoginJson> response) {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx fieldMapResultLogin 请求成功");
                    LoginJson loginJson = response.body();
                    if (loginJson != null) {
                        Log.d(TAG, "cfx LoginJson = " + loginJson.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginJson> call, Throwable t) {
                Log.d(TAG, "cfx fieldMapResultLogin 请求失败 " + t);
            }
        });
    }

    private MultipartBody.Part createMultipart(String path, String key) {
        File file = new File(path);
        MediaType mediaType = MediaType.parse("image/jpeg");
        RequestBody requestBody = RequestBody.create(mediaType, file);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
        return part;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值