eclipse如何使用retrofit

2025-11-21 08:58:07

1、权限

在AndroidManifest.xml中请求络权限 :

<uses-permission android:name="android.permission.INTERNET" />  

eclipse如何使用retrofit

2、下载最新的jar,搜索"Retrofit jar"下载

记得添加okhttp依赖和其内部依赖okio

eclipse如何使用retrofit

1、创建一个Retrofit实例

public static final String BASE_URL = "http://api.myservice.com";  

Retrofit retrofit = new Retrofit.Builder()  

    .baseUrl(BASE_URL)  

    .build();  

eclipse如何使用retrofit

2、把Gson Converter 作为一个独立的依赖添加进来。

compile 'com.google.code.gson:gson:2.4'  

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'  

3、使用addConverterFactory把它添加进来:

public static final String BASE_URL = "http://api.myservice.com";  

Retrofit retrofit = new Retrofit.Builder()  

    .baseUrl(BASE_URL)  

    .addConverterFactory(GsonConverterFactory.create())  

    .build();  

eclipse如何使用retrofit

1、Endpoints实现了转换HTTP API为Java接口。

Retrofit有5种请求类型注解:GET、POST、PUT、DELETE和HEAD,用法如下

相对URL。

eclipse如何使用retrofit

2、@GET("users/list")  

查询参数

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

参数在路径中

@GET("group/{id}/users")  

Call<List<User>> groupList(@Path("id") int groupId);  

也可以添加查询参数

@GET("group/{id}/users")  

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);  

多个参数组合为Map

@GET("group/{id}/users")  

Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);  

使用@Body将json字符串解析为一个对象作为参数

3、@POST("users/new")  

Call<User> createUser(@Body User user);  

使用@FormUrlEncoded发送表单,同时@Field指参数值。

@FormUrlEncoded  

@POST("user/edit")  

Call<User> getUser(@Field("name") String name, @Field("password") String password);  

使用Map将过多的表单参数组合到一起

@FormUrlEncoded  

@POST("user/edit")  

Call<User> getUser(@FieldMap Map<String, String> map);  

@Multipart文件上传,@Part指定文件路径

@Multipart  

@POST("/user/edit")  

Call<User> upload(@Part("image\"; filename=\"文件名.jpg") RequestBody file);  

@MapPart批量上传

@Multipart  

@POST("/user/edit")  

Call<User> upload(@PartMap Map<String, RequestBody> params);  

[java] view plain copy

RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imgFile);  

map.put("image\"; filename=\""+imgFile.getName()+"", fileBody);  

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢