Retrofit网络请求使用

Retrofit是最近项目需要而用到的,之前对这种框架一无所知,现在就让我们一起来探索Retrofit使用。
本文参考:http://blog.csdn.net/qq_17766199/article/details/49946429
http://www.open-open.com/lib/view/open1435381942341.html

Retrofit是什么?

    首先,我们应该先要了解Retrofit是什么,才能逐渐深入理解并运用;经过一番查询了解,发现它是类似Volley和AsyncHttp类似的网络请求框架,但是Retrofit更加简单,效率更高,优于前两者。
    Retrofit是由Square开发的Android和Java的REST客户端库。Retrofit库相对于其他网络库来说,非常简单,更易让我们开发者快速掌握;它支持GET/POST/PUT/DELETE等多种请求。

Retrofit的特点(我们为什么选择它)

    1、性能好,处理数据快;
    2、使用REST API时非常方便;
    3、传输层默认搭配OKHttp;
    4、支持NIO;
    5、速度比volley更快;
    6、拥有出色的API文档和社区支持;
    7、如果程序中集成OKHttp,Retrofit默认使用OKHttp处理其他网络层请求;
    8、默认使用Gson。

对Retrofit的使用

    好!我们大家都简单的了解了Retrofit是什么和它自身的特点,接下来我们步入正题:如何使用它?

1、Retrofit 2.0之后必须配置权限:首先确保AndroidManifest.xml中请求网络权限:

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

2、Studio用户,在app/build.gradle文件中添加如下代码:

dependencies {
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    compile 'com.squareup.okio:okio:1.6.0'
}

注意:1.Retrofit必须使用okhttp请求了,如果项目中没有okhttp的依赖的话,肯定会出错 。
2.okhttp内部依赖okio所以也要添加。

3、使用实例

1)创建Retrofit实例
public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .build();

如果你想接收json 结果并解析成DAO,你必须把Gson Converter 作为一个独立的依赖添加进来。

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

这里是Square提供的官方Converter modules列表。选择一个最满足你需求的。

Gson: com.squareup.retrofit:converter-gson

Jackson: com.squareup.retrofit:converter-jackson

Moshi: com.squareup.retrofit:converter-moshi

Protobuf: com.squareup.retrofit:converter-protobuf

Wire: com.squareup.retrofit:converter-wire

Simple XML: com.squareup.retrofit:converter-simplexml

你也可以通过实现Converter.Factoty接口来创建一个自定义的converter。

然后使用addConverterFactory把它添加进来:

public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
2)定义Endpoints,实现了转换HTTP API为Java接口

Retrofit提供了5种内置的注解:GET、POST、PUT、DELETE和HEAD,在注解中指定的资源的相对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);

也可以添加查询参数

@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注解指定一个对象作为Http请求的请求体

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

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

@FormUrlEncoded
@POST("user/edit")
Call<User> getUser(@Field("name") String name, @Field("password") String password);

使用@FormUrlEncoded发送表单数据时,表单项过多时可以使用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);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imgFile);
map.put("image\"; filename=\""+imgFile.getName()+"", fileBody);
3)访问 API
public interface MyApiEndpointInterface {
    // Request method and URL specified in the annotation
    // Callback for the parsed response is the last parameter
    @GET("/users/{username}")
    Call<User> getUser(@Path("username") String username);
}
MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class);

异步请求这个API

String username = "sarahjean";
Call<User> call = apiService.getUser(username);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Response<User> response) {
        int statusCode = response.code();
        User user = response.body();  
    }
    @Override
    public void onFailure(Throwable t) {
        // Log error here since request failed
    }
});

同步请求

String username = "sarahjean"; 
Call<User> call = apiService.getUser(username);
User user = call.execute();

4.注意

(1)我们在同步方法使用时可以直接调用execute方法,但是这个方法只能调用一次。解决办法:需要用clone方法生成一个新的之后在调用execute方法:

Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
response = call.execute();
// This will throw IllegalStateException:
response = call.execute();
Call<List<Contributor>> call2 = call.clone();
// This will not throw:
response = call2.execute();

(2)当我们执行的同步或异步加入队列后,可以随时使用cancel方法取消请求:

Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");

call.enqueue(...);
// or...
call.execute();

// later...
call.cancel();

好了,至此我们大致理解并简单的使用Retrofit,如果你想灵活运用并且深入理解Retrofit需要再实际开发中多运用(实践出真知)!
感谢:android开源社区,CSDN博客,OPEN社区提供的帮助!希望志同道合的同志共同为android技术做出贡献。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值