Retrofit网络请求框架基础操作
2016-05-05 14:20
633 查看
Retrofit网络请求框架基础操作
RetrofitRetrofit 是一套 RESTful 架构的 Android(Java) 客户端实现,基于注解,提供 JSON to POJO(Plain Ordinary Java Object ,简单 Java 对象),POJO to JSON,网络请求(POST,GET, PUT,DELETE 等)封装。
优点:Retrofit 是一套注解形的网络请求封装库,让我们的代码结构更给为清晰。它可以直接解析JSON数据变成JAVA对象,甚至支持回调操作,处理不同的结果。
基础操作
- Demo中使用的接口地址 :http://apis.baidu.com/heweather/weather/free
- 添加依赖
compile 'com.squareup.okhttp3: okhttp:3.2.0' compile 'com.squareup.retrofit2: retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2: converter-gson:2.0.0-beta3'
建议:如果API返回的是JSON数据,可以利用AndroidStudio的插件GsonFormat,将JSON数据转换为Java对象。
创建请求接口
public interface NetRequest { @GET("/heweather/weather/free?/") Call<WeatherInfo> getWeather(@Header("apiKey")String apiKey, @Query("city")String city); }
讲解:
1. @GET()用来填写需要访问的接口
2. @Header用来添加Header
3. @Query用来添加输入请求的标识
创建网络接口服务封装类
public class RetrofitWrapper {
private static RetrofitWrapper instance;
private Context mContext;
private Retrofit retrofit;
private RetrofitWrapper() {
Gson gson = new Gson();
//创建Retrofit对象
retrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static RetrofitWrapper getInstance() {
if (instance == null) {
synchronized (RetrofitWrapper.class){
if (instance==null){
instance = new RetrofitWrapper();
}
}
}
return instance;
}
//创建请求接口的对象
public T create(final Class service) {
return retrofit.create(service);
}
}
讲解:
1. BASE_URL:接口的API主机地址
创建功能模块类
public class WeatherInfoModel {
private static WeatherInfoModel weatherInfoModel;
private NetRequest netRequest;
public WeatherInfoModel(Context context) { netRequest = (NetRequest) RetrofitWrapper.getInstance().create(NetRequest.class); } public static WeatherInfoModel getInstance(Context context) { if (weatherInfoModel == null) { weatherInfoModel = new WeatherInfoModel(context); } return weatherInfoModel; } /** * 查询天气 * * @param weatherInfoReq * @return */ public Call<WeatherInfo> queryWeather(WeatherInfoReq weatherInfoReq) { Call<WeatherInfo> infoCall = netRequest.getWeather(weatherInfoReq.apiKey, weatherInfoReq.city); return infoCall; }
}
Activity类
public class MainActivity extends Activity {
private Button request;
private TextView tv;
private WeatherInfoModel weatherInfoModel;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); weatherInfoModel = WeatherInfoModel.getInstance(getApplicationContext()); initViews(); initParams(); initEvent(); } private void initEvent() { request.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //创建访问的API请求 Call<WeatherInfo> callWeather= weatherInfoModel.queryWeather(initParams()); final Gson gson = new Gson(); //发送请求 callWeather.enqueue(new Callback<WeatherInfo>() { @Override public void onResponse(Call<WeatherInfo> call, Response<WeatherInfo> response) { if(response.isSuccessful()){ WeatherInfo result = response.body(); if(result!=null){ tv.setText(gson.toJson(result)); } } } @Override public void onFailure(Call<WeatherInfo> call, Throwable t) { } }); } }); }
/*
*初始化请求参数
*/
private WeatherInfoReq initParams() {
WeatherInfoReq weatherInfoReq = new WeatherInfoReq();
weatherInfoReq.apiKey = Constant.API_KEY;
weatherInfoReq.city = Constant.CITY;
return weatherInfoReq;
}
/*
*初始化控件
*/
private void initViews() {
request = (Button) this.findViewById(R.id.request);
tv = (TextView) this.findViewById(R.id.tv);
}
}
PS:
1.本文并未贴上所用到的Bean类和一些用到的常量,如需请到个人的github上下载源码
2.本文参考http://blog.csdn.net/u011974987/article/details/50895633
相关文章推荐
- 北京大学信息科学技术学院本科生课程体系课程大纲选登——计算机网络与WEB技术
- 神经网络和深度学习-学习总结
- TCP的流量控制
- 网络安全的重要性持续提升,净网ing
- HTTP 错误 404.2 - Not Found 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页
- TCP的拥塞控制
- 计算机网络——运输层
- Servlet & JSP - HttpSession
- 使用Socket发送Http请求
- 使用Socket发送Http请求
- TCP全局同步
- TCP/IP协议浅入浅出1
- Android M提示网络变化
- 【fastweixin框架教程3】JAVA进行HTTPS网站访问,PKIX path building failed解决方法
- Spring mvc,uploadifive 文件上传实践(转自:https://segmentfault.com/a/1190000004503262)
- Spring mvc,uploadifive 文件上传实践(转自:https://segmentfault.com/a/1190000004503262)
- tcp协议栈
- HttpClient4 警告: Invalid cookie header 的问题解决
- RxJava+Retrofit+Gson实现网络请求
- Winsock网络编程客户端