Retrofit是一个三方网络请求框架,类似于Volley之类的。
添加依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
请求代码
public class RetrofitActivity extends BaseActivity {
private static final String BASE_URL = "http://www.tngou.net/tnfs/api/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit);
query();
}
private void query() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())//解析方法
.baseUrl(BASE_URL)//主机地址
.build();
//2.创建访问API的请求
RequestService service = retrofit.create(RequestService.class);
Call<SingleImageBean> call = service.getImage("171");
//3.发送请求
call.enqueue(new Callback<SingleImageBean>() {
@Override
public void onResponse(Call<SingleImageBean> call, Response<SingleImageBean> response) {
//4.处理结果
if (response.isSuccess()) {
SingleImageBean result = response.body();
if (result != null) {
Log.v("-->", result.toString());
}
}
}
@Override
public void onFailure(Call<SingleImageBean> call, Throwable t) {
}
});
}
}
public interface RequestService {
@GET("show")
Call<SingleImageBean> getImage(@Query("id") String id);
}
请求结果
小结
上面service.getImage(“171”) 方法经过拼装后其实访问的是http://www.tngou.net/tnfs/api/show?id=171
Get请求方式
@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);
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
Post请求方式
@POST("users/new")
Call<User> createUser(@Body User user);