Retrofit 的使用详解(下载 多文件上传)

来源:互联网 发布:asp商城网站源码 编辑:程序博客网 时间:2024/05/16 16:58

demo地址:
https://github.com/luhaoaimama1/ZoneStudio/blob/master/Android_Zone_Test/src/com/example/mylib_test/activity/http/retrofit/MyRetrofitTest.java

Retrofit提供了5种内置的注解:GET、POST、PUT、DELETE和HEAD,在注解中指定的资源的相对URL

url与参数小总结

@GET("users/list")  

也可以在URL中指定查询参数

@GET("users/list?sort=desc") 

请求的URL可以在函数中使用替换块和参数进行动态更新,替换块是{ and }包围的字母数字组成的字符串,相应的参数必须使用相同的字符串被@Path进行注释

@GET("group/{id}/users")  Call<List<User>> groupList(@Path("id") int groupId);  

准备工作:

Retrofit初始化

    public static ZoneApiInterface getClient(){        Retrofit retrofit2 = new Retrofit.Builder()                .baseUrl(Constant.ADDRESS_RetrofitClient)                .addConverterFactory(GsonConverterFactory.create())//                .client(ok.getClient())                .build();        return retrofit2.create(ZoneApiInterface.class);    }

API接口

 public interface ZoneApiInterface {...}

callback回调

    static Callback callback =new Callback<Data>() {        @Override        public void onResponse(Call<Data> call, Response<Data> response) {            System.out.println("url:"+  call.request().url()+"\t --->"+new Gson().toJson(response.body())+"\n\n");        }        @Override        public void onFailure(Call<Data> call, Throwable t) {            t.printStackTrace();        }    };

get请求

@Query
查询参数既 url?后边的

@GET("{user}") Call<Data> getZone(@Path("user") String user, @Query("name") String str);getClient().getZone("log","Zone").enqueue(callback);

@QueryMap

 @GET("{user}")Call<Data> getZone(@Path("user") String user, @QueryMap Map<String,String> map);retrofit2.Call<Data> call2 =  getClient().getZone("log", map);//返回的时候call 可以灵活运用

@Url

在Retrofit 2.0添加了一个新的注解:@Url,它允许我们直接传入一个请求的URL。这样以来我们可以将上一个请求的获得的url直接传入进来。方便了我们的操作。

@GET

Call<Data> getZoneUrl(@Url String str);getClient().getZoneUrl("http://101.40.6.224:8089/Test/log"+"?a=1").enqueue(callback);

这个会无视 这里写图片描述

POST

@Body
可以通过@Body注解指定一个对象作为Http请求的请求体

@POST("users/new")  Call<User> createUser(@Body User user);  

@Body map的时候

@POST(“{user}”)

 Call<Data> postZone(@Path("user") String user, @Body Map<String,String> map);  getClient().postZone("log", map).enqueue(callback);

upLoad

1.最标准的
@POST(“log”)

 Call<Data> postZoneFile( @Body MultipartBody mb);//upload最为标准的File file = new File("D:\\psb.jpg");File file2 = new File("D:\\mei.jpg");        //多个文件上传(已此为标准)  文件的时候item.isFormField()=false        MultipartBody.Builder form = new MultipartBody.Builder();        form.setType(MultipartBody.FORM);        form.addFormDataPart("keyName","Zone");        form.addFormDataPart("file","gaga.jpg", RequestBody.create(MediaType.parse("image/*"), file1));        form.addFormDataPart("file2","meinv.jpg", RequestBody.create(MediaType.parse("image/*"), file));        getClient().postZoneFile(form.build()).enqueue(callback);

2.Multipart官方的不太靠谱的 和上边仅仅是服务器的标志 不一样 item.isFormField()=true

       @Multipart        @POST("log")        Call<Data> sendFile(@Part(value = "myFile",encoding = "utf-8") RequestBody file);//upload        @Multipart        @POST ("log")        Call<Data> sendFiles (@PartMap Map<String, RequestBody> params);      //另一种方式 不太靠谱的 和上边仅仅是服务器的标志 不一样 item.isFormField()=true        HashMap<String, RequestBody> mapFile = new HashMap<>();        mapFile.put("keyName", RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),"Zone"));        mapFile.put("file1",RequestBody.create(MediaType.parse("image/*"), file));        getClient().sendFiles(mapFile).enqueue(callback);//        _-------------单文件上传 和第二一样不标准-------------------        getClient().sendFile(RequestBody.create(MediaType.parse("image/*"), file)).enqueue(callback);

download

 @GET@Streamingpublic Call<ResponseBody> down(@Url String url);//downLoadstatic String downUrl = "http://down.360safe.com/360/inst.exe";        //好使        getClient().down(downUrl).enqueue(new Callback<ResponseBody>() {            @Override            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {                File file = new File("D:\\");                if (file.exists()) {                    System.out.println("you ");                } else {                    System.out.println("没有");                }                try {                    System.out.println(response.body().string());                } catch (IOException e) {                    e.printStackTrace();                }            }            @Override            public void onFailure(Call<ResponseBody> call, Throwable t) {            }        });

Form encoded

我们可以使用@FormUrlEncoded注解来发送表单数据。使用 @Field注解和参数来指定每个表单项的Key,value为参数的值。

当我们有很多个表单参数时可以通过@FieldMap注解和Map对象参数来指定每个表单项的Key,value的值。
//@Field 这个应该和@body一样什么也能上传文件吧没尝试

        @FormUrlEncoded        @POST("log")        Call<Data> formUrlEncoded(@Field("name") String name, @Field("password") String password);        @FormUrlEncoded        @POST("log")        Call<Data> formUrlEncodedFile(@FieldMap Map<String, String> map);   private static void formUrlEncoded(Map<String, String> map) {        getClient().formUrlEncoded("ZoneForm", "123456").enqueue(callback);        getClient().formUrlEncodedFile(map).enqueue(callback);    }
2 0
原创粉丝点击