源代码路径
https://github.com/huxiubo1980/RetrofitDemoXiubo/
添加依赖
build.gradle添加依赖
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'
接口声明
public interface MovieService {
/**请求方法*/
@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
}
调用接口
在MainActivity调用(异步调用)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create()) /** json解析*/
.build();
/**这里是interface,so,需要创建一个代理*/
MovieService movieService = retrofit.create(MovieService.class);
/**拿到代理对象后就可以调用方法了*/
Call<MovieEntity> call = movieService.getTopMovie(0, 2);
call.enqueue(new Callback<MovieEntity>() {
@Override
public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
Log.d(TAG, "respose = " + response.body().getTitle());
tv.setText(response.body().getTitle());
}
@Override
public void onFailure(Call<MovieEntity> call, Throwable t) {
Log.d(TAG, "onFailure = " + t.getMessage());
}
});
同步调用
try {
Response<ResponseBody> response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
权限申请
<!-- 网络状态权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
网友评论