Retrofit-入门使用
来源:互联网 发布:mac可以抠图的软件 编辑:程序博客网 时间:2024/06/06 11:02
- 在模块目录下的build.gradle
dependencies { compile "com.squareup.retrofit2:retrofit:2.1.0" compile "com.squareup.retrofit2:converter-gson:2.1.0"}
2.请求服务接口类-注解对应服务器接口
public interface HttpService { String SERVER_HOST = "http://xx.xx.xx.xx"; String CONTENT_PATH = "/xx"; class factory { private static volatile HttpService instance; public static HttpService getHttpService() { if (instance == null) { synchronized (HttpService.class) { if (instance == null) { Retrofit rf = new Retrofit.Builder().baseUrl(HttpService.SERVER_HOST).build(); HttpService hs = rf.create(HttpService.class); instance = hs; } } } return instance; } } @GET(CONTENT_PATH + "/api/app/list?type=sense") Call<ResponseBody> list(@Header("DAAUTH") String token); @GET(CONTENT_PATH + "/api/app/navlist?type=sense") Call<ResponseBody> favlist(@Header("DAAUTH") String token); @GET(CONTENT_PATH + "/api/app/fav?type=sense") Call<ResponseBody> fav(@Header("DAAUTH") String token, @Query("appid") String appid); @GET(CONTENT_PATH + "/api/app/unfav?type=sense") Call<ResponseBody> unfav(@Header("DAAUTH") String token, @Query("appid") String appid); @GET(CONTENT_PATH + "/api/auth/login/") Call<ResponseBody> loginByBasic(@Header("DAAUTH") String basic); @GET(CONTENT_PATH + "/api/auth/login/") Call<ResponseBody> loginByToken(@Header("DAAUTH") String token);}
这里采用了一个单例模式,在定义的接口服务类中声明一个内部类factory来定义与返回HttpService的单例,内部直接使用了Retrofit进行创建。
3.具体调用
HttpService hs = HttpService.factory.getHttpService();String token = "token 5cd61e10d242937a13ec40f671db19d5";Call<ResponseBody> call = hs.list(token);call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { ResponseBody body = response.body(); if (body != null) { Log.d(TAG, body.string()); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { if(t.getClass().equals(SocketTimeoutException.class)) { Toast.makeText(MainActivity.this, "Connect Timeout...", Toast.LENGTH_SHORT).show(); String msg = t.getMessage(); Log.e(TAG, msg); } }});
简单的使用方法,Retrofit有更多的接口方法可供使用。
阅读全文
0 0
- Retrofit使用入门
- Retrofit使用入门
- Retrofit-入门使用
- Retrofit网络框架入门使用
- Retrofit简单入门及使用
- Retrofit使用教程(一)- Retrofit入门详解
- Retrofit使用教程(一)- Retrofit入门详解
- 简单入门使用Retrofit+ rxjava 下载图片
- 网络请求框架 Retrofit 2 使用入门
- Retrofit入门
- retrofit入门
- Retrofit入门
- Retrofit入门
- Retrofit使用
- Retrofit使用
- Retrofit使用
- Retrofit使用
- Retrofit使用
- hdu 5726 GCD 解题报告
- Java并发编程:并发容器之CopyOnWriteArrayList
- canvas.save() canvas.restore() 作用
- 第01讲 mysql基本介绍与安装等
- Android学习之添加动画一
- Retrofit-入门使用
- maven resources profiles
- Android 加载SVG动画
- 判断线程池中的线程是否全部执行完毕
- 人工智能的五大核心技术
- Android studio编译错误二:Error: The WIFI_SERVICE must be looked up on the Application
- javascript call函数
- 第02讲 mysql的基本使用
- leetcode 540. Single Element in a Sorted Array