Retrofit简单使用

官网 http://square.github.io/retrofit/

一、配置
APP build.gradle

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

//为了解析为gson格式

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

二、使用
1.创建接口,提供请求方法,参数

public interface ApiService {
    @GET("service/getIpInfo.php")
    Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);
}

public class GetIpInfoResponse {
    public IpInfo data;
}

public class IpInfo {
    public String country;
    public String country_id;
    public String area;
    public String area_id;
    public String ip;
}

2.创建Retrofit

Retrofit是final类,没有public构造方法,只能使用new Retrofit.Builder()创建,可以指定跟地址baseurl,返回的类型addConverterFactory,错误处理,请求拦截器等,必须有的是baseUrl()和addConverterFactory()方法.

 Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(ENDPOINT)  //加URL
    .addConverterFactory(GsonConverterFactory.create())  //转化为Gson
    .build();

3.实现接口,创建了执行请求对象的代理

ApiService apiService = retrofit.create(ApiService.class);

4.处理请求结果。

调用接口中方法得到Call,每个Call可以发送一个同步或异步的请求。
接口返回的内容response.body()

Call<GetIpInfoResponse> call = apiService.getIpInfo("1.1.1.1");
call.enqueue(new Callback<GetIpInfoResponse>() {
    @Override
    public void onResponse(Response<GetIpInfoResponse> response, Retrofit retrofit) {
        GetIpInfoResponse getIpInfoResponse = response.body();
        tv_retrofit.setText(getIpInfoResponse.data.toString());
    }

    @Override
    public void onFailure(Throwable t) {
         tv_retrofit.setText("error" + t);
    }
});

三、API 描述
1.请求方式,五种:GET, POST, PUT, DELETE, HEAD

注解明确了URL地址

1.@GET

添加参数 @Query(“ip”) String ip,如果参数是Map,@QueryMap Map

@GET("service/getIpInfo.php")
Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);

把参数添加在注解中(写死的地址)

@GET("service/getIpInfo.php?ip=1.1.1.1")
Call<GetIpInfoResponse> getIpInfo();

URL中有可替换的字段,使用{}

@GET("{id}/getIpInfo.php")
Call<GetIpInfoResponse> getIpInfo(@Path("id") String id,@Query("ip") String ip);

2.@POST

请求体,使用 @Body

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

可以使用完整路径,在创建Retrofit时的baseURL会被忽略(相同的URL会正确访问,不同的会连接超时,错误的URL会出错,,创建Retrofit时会校验URL格式)

@POST("http://ip.taobao.com/service/getIpInfo.php?ip=1.1.1.1")
Call<GetIpInfoResponse> getIpInfo();

表单数据 @FormUrlEncoded在方法上注解,@Field用来描述键值对

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

四、同步、异步

在Retrofit2之前定义一个同步的函数

public interface GitHubService {  
    @POST("/list")  
   返回类型 loadRepo();         
}  

异步函数定义

public interface GitHubService {      
    @POST("/list")  
    void loadRepo(Callback<Repo> cb);      
} 

Retrofit2 同步异步方法定义一个接口,返回的类型为Call

public interface GitHubService { 
    @POST("/list")  
    Call<Repo> loadRepo();  
} 

关于调用

call.enqueue() 为异步调用,没有返回的类型;

call.execute() 为同步调用,有返回的类型,Response。

call.clone () 一个call只能被使用一次,重复请求接口时使用,不能直接对call操作call.clone().enqueue()后处理。

公参

 Interceptor headerInterceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder requestBuilder = originalRequest.newBuilder()
.header("AppType", "TPOS")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.method(originalRequest.method(), originalRequest.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
};

//设置头

builder.addInterceptor(headerInterceptor );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值