retorfit

来源:互联网 发布:淘宝网齐峰堂足宝粉 编辑:程序博客网 时间:2024/05/21 07:09

    retrofit
    Retrofit是一个不错的网络请求库就是对okhttp做了一层封装。把网络请求都交给给了Okhttp
    优点是 retrofit简化了网络请求流程,解耦的更彻底:比方说通过注解来配置请求参数
    Retrofit的使用就是以下几步:
 
    定义接口,参数声明,Url都通过Annotation(注解)指定
    Retrofit提供的请求方式注解有@GET和@POST,参数注解有@PATH和@Query等:    
    用来返回我们的Call对象从而将数据返回


    然后通过创建一个Retrofit
    接下来我们用这个Retrofit对象创建一个RequestSerives接口对象,也就是我们之前定义的那个接口,并且得到我 们  的Call对象;

    利用得到的Call对象,然后我们就发出网络请求了:
    同步需要运行在子线程否则就会crash
    BookSearchResponse response = call.execute().body();

    发送请求之后数据就在成功回调方法里面取到  根据业务取出需要的数据。





 public interface FileUploadService {   @Multipart @POST("upload") Call<ResponseBody> upload(@Part("description") RequestBody description,                          @Part MultipartBody.Part file);}







先看一个基本的用法:

// 创建 RequestBody,用于封装构建RequestBodyRequestBody requestFile =        RequestBody.create(MediaType.parse("multipart/form-data"), file);// MultipartBody.Part  和后端约定好Key,这里的partName是用imageMultipartBody.Part body =        MultipartBody.Part.createFormData("image", file.getName(), requestFile);// 添加描述String descriptionString = "hello, 这是文件描述";RequestBody description =        RequestBody.create(                MediaType.parse("multipart/form-data"), descriptionString);// 执行请求Call<ResponseBody> call = service.upload(description, body);call.enqueue(new Callback<ResponseBody>() {    @Override    public void onResponse(Call<ResponseBody> call,                           Response<ResponseBody> response) {        Log.v("Upload", "success");    }    @Override    public void onFailure(Call<ResponseBody> call, Throwable t) {        Log.e("Upload error:", t.getMessage());      }    });}

0 0
原创粉丝点击