squareup 推出 retrofit2 已经有一段时间了,现在的版本比较稳定,没有什么大坑了。网络上的教程要么太简单,只是个Demo;要么有些落时,要么复用性比较差,所以自己写个教程,供大家参考。代码已上传至 https://github.com/Alex9Xu/RetrofitDemo

1. 首先在build.gradle引入依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

注意,这里的 logging 用于输出网络交互的Log,对于开发调试极其有用。之前retrofit2因为不能输出Log被人嫌弃了很久,各高手实现了几种打印Log的方式,现在总算有官方的了。

2. 这是工具类

package com.alex9xu.hello.net;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable; import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; import com.alex9xu.hello.config.AppConfigInterface;
import com.alex9xu.hello.utils.LogHelper; import java.io.IOException;
import java.lang.ref.WeakReference; /**
* Created by Alex9Xu@hotmail.com on 2016/7/13
*/
public class RetrofitBase {
private static final String TAG = "RetrofitBase"; private static Retrofit mRetrofit;
// private static Dialog mLoadingDialog;
private static WeakReference<Context> mContextRef; public static Retrofit retrofit() {
if (mRetrofit == null) {
OkHttpClient client; // Notice: The only differ of debug is: HttpLoggingInterceptor
// Common Params: "version" and "server_call_version" will in every request
if(!AppConfigInterface.isDebug) {
client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("call_version", AppConfigInterface.TO_SERVER_VERSION)
.addQueryParameter("deviceType", AppConfigInterface.DEVICE_TYPE)
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("user-agent", "android")
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
} else {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(logging)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("version", AppConfigInterface.TO_SERVER_VERSION)
.addQueryParameter("deviceType", AppConfigInterface.DEVICE_TYPE)
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("user-agent", "android")
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
} mRetrofit = new Retrofit.Builder()
.baseUrl(AppConfigInterface.BASE_COM_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return mRetrofit;
} // Encapsulation Request and Response
public static <T> void AddToEnqueue(Call<T> baseCall, Context context, boolean isShowDlg,
final NetRequestListener listener) {
mContextRef = new WeakReference<>(context);
// if(isShowDlg && null == mLoadingDialog && null != mContextRef.get()) {
// mLoadingDialog = DialogUtil.showLoginDialog(mContextRef.get());
// mLoadingDialog.getWindow().setBackgroundDrawable(new BitmapDrawable());
// }
// if(isShowDlg) {
// mLoadingDialog.show();
// } baseCall.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, retrofit2.Response<T> response) {
LogHelper.d(TAG, "toEnqueue, onResponse:");
if (null != response.body()) {
if(response.code() == 200) {
LogHelper.d(TAG, "toEnqueue, onResponse Suc");
// if(null != mLoadingDialog) {
// mLoadingDialog.dismiss();
// }
listener.onRequestSuc(response.code(), response);
} else {
LogHelper.d(TAG, "toEnqueue, onResponse Fail:" + response.code());
// if(null != mLoadingDialog) {
// mLoadingDialog.dismiss();
// }
listener.onRequestFail(response.code(), response.message());
}
} else {
LogHelper.d(TAG, "toEnqueue, onResponse Fail");
// if(null != mLoadingDialog) {
// mLoadingDialog.dismiss();
// }
listener.onRequestFail(response.code(), response.message());
}
} @Override
public void onFailure(Call<T> call, Throwable t) {
LogHelper.d(TAG, "toEnqueue, onFailure Fail");
// if(null != mLoadingDialog) {
// mLoadingDialog.dismiss();
// }
listener.onRequestFail(AppConfigInterface.RESULT_FAIL_UNKNOW, null);
}
});
} public static void stopLoadingDlg(Context context) {
// if(null != mContextRef && context == mContextRef.get() && null != mLoadingDialog) {
// mLoadingDialog.dismiss();
// mLoadingDialog = null;
// }
} }

讲解一下:

(1) 通过 addInterceptor 实现的打印日志及加入多个公共参数功能。

(2) 除了含有 HttpLoggingInterceptor 外,测试的和正式的,没有任何区别。通过全局变量控制是否为正式环境,如果是正式环境则不输出网络交互相关的Log。

(3) 可以通过 addQueryParameter("deviceType", "0") 的形式加入多个公共参数,这样所有的请求都会带该参数。

(4) 这里 BASE_COM_URL 是 http://test.hello.com/ 的形式。

3. 使用方式:

(1) 先写接口

package com.alex9xu.hello.net.apis;

import android.support.v4.util.ArrayMap;
import com.alex9xu.hello.config.AppConfigInterface;
import com.alex9xu.hello.model.WeatherResult; import retrofit2.Call; import retrofit2.http.GET;
import retrofit2.http.QueryMap; /**
* Created by Alex9Xu@hotmail.com on 2016/7/14
*/ public interface CityWeatherApi {
@GET(AppConfigInterface.GET_WEATHER)
Call<WeatherResult> getClassify(@QueryMap ArrayMap<String,String> paramMap);
}

这里通过Get提交参数,参数存储在Map里,可以添加多组参数。注意,我使用了ArrayMap,这是Android里特有的一种形式,内存占用只有HashMap的十分之一左右。

String CLASSIFYLIST = "query/classify.html";

(2) 再写返回值结构

package com.alex9xu.hello.model.Entity;

/**
* Created by Alex9Xu@hotmail.com on 2016/7/18
*/
public class Weatherinfo {
private String city;
private String cityid;
private String temp;
private String WD;
private String WS;
private String SD;
private String WSE;
private String time;
private String isRadar;
private String Radar;
private String njd;
private String qy; public String getCity() {
return city;
} public String getTemp() {
return temp;
}
}
package com.alex9xu.hello.model;

import com.alex9xu.hello.model.Entity.Weatherinfo;

/**
* Created by Alex9Xu@hotmail.com on 2016/7/18
*/
public class WeatherResult { private Weatherinfo weatherinfo; public Weatherinfo getWeatherinfo() {
return weatherinfo;
} }

返回的数据写成如上形式,以利于复用。

(3) 调用

import com.alex9xu.test.model.ClassifyListResult;
import com.alex9xu.test.model.entity.ClassfiyBean;
import com.alex9xu.test.net.ClassifyApi;
import com.alex9xu.test.net.RetrofitBase;
/** * Created by Alex9Xu@hotmail.com on 2016/7/14
*/
public class MainActivity extends BaseActivity {
// Note: make all the Activities extends BaseActivity to manage
private static final String TAG = "MainActivity"; private TextView mTvwShowInfo;
private Call<WeatherResult> mWeatherCall;
  ...
private void getData() {
// Notice: ArrayMap requires less memory in Android compare with HashMap (about 10%)
CityWeatherApi classifyApi = RetrofitBase.retrofit().create(CityWeatherApi.class);
ArrayMap<String,String> paramMap = new ArrayMap<>();
paramMap.put("sortType", "1");
paramMap.put("uid", "654321");
mWeatherCall = classifyApi.getClassify(paramMap); RetrofitBase.AddToEnqueue(mWeatherCall, MainActivity.this, true, new NetRequestListener() {
@Override
public void onRequestSuc(int code, Response response) {
LogHelper.d(TAG, "onRequestSuc");
Response<WeatherResult> resultResponse = response;
if(null != resultResponse.body().getWeatherinfo()) {
Weatherinfo info = resultResponse.body().getWeatherinfo();
StringBuilder strBld = new StringBuilder();
strBld.append(info.getCity());
strBld.append(getString(R.string.temperature));
strBld.append(getString(R.string.colon));
strBld.append(info.getTemp());
mTvwShowInfo.setText(strBld.toString());
}
} @Override
public void onRequestFail(int code, String reason) {
LogHelper.d(TAG, "onRequestFail: " + code + ", " + reason);
}
});
} @Override
protected void onStop() {
super.onStop();
// Notice: If the web operate is to update UI, you can cancel it when onStop
mWeatherCall.cancel();
}
...

讲解:会拼接成 https://test.hello.com/query/classify.html?uid=654321&version=1.0&Id=123456&deviceType=0 ,注意,其中两项是公共参数。

好了,这样就可以正常运行了。

retrofit2 使用教程 及 Android 网络架构搭建 (原创)的更多相关文章

  1. Retrofit2.0+RxJava+Dragger2实现不一样的Android网络架构搭建

    Tamic :csdn http://blog.csdn.net/sk719887916 众所周知,手机APP的核心就在于调用后台接口,展示相关信息,方便我们在手机上就能和外界交互.所以APP中网络框 ...

  2. 基于Retrofit2.0+RxJava+Dragger2实现不一样的Android网络构架搭建(转载)

    转载请注明出处:http://blog.csdn.net/finddreams/article/details/50849385#0-qzone-1-61707-d020d2d2a4e8d1a374a ...

  3. android 学习运用海马模拟器教程与android环境的搭建

    第三方海马玩模拟器 第一天的学习android采用的模拟器是海马,因此就分享给大家海马模拟器的相关步骤: 海马玩模拟器官网: http://droid4x.haimawan.com 下载相关平台的模拟 ...

  4. Android网络编程(一)HTTP协议原理

    相关文章 Android网络编程(一)HTTP协议原理 Android网络编程(二)HttpClient与HttpURLConnection Android网络编程(三)Volley使用方法全解析 A ...

  5. Android Navigation 架构组件入门教程

    Android Navigation 架构组件入门教程 版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:https://www.cnblogs.com/cavalier-/p/1 ...

  6. Android 网络教程: 开始

    原文:Android Networking Tutorial: Getting Started 作者:Eunice Obugyei 译者:kmyhy 从 API 级别 1 开始,网络始终是 Andro ...

  7. 转---详细的Android开发环境搭建教程

    五步搞定Android开发环境部署——非常详细的Android开发环境搭建教程 引言   在windows安装Android的开发环境不简单也说不上算复杂,本文写给第一次想在自己Windows上建立A ...

  8. Android基础新手教程——1.2 开发环境搭建

    Android基础新手教程--1.2 开发环境搭建 标签: Android基础新手教程 如今主流的Android开发环境有: ①Eclipse + ADT + SDK ②Android Studio ...

  9. Android开发环境搭建篇详尽的教程实例汇

    原文链接:http://android.eoe.cn/topic/android_sdk 一.android开发环境搭建图文教程整理篇: 1.Android开发环境搭建全程演示(jdk+eclip+a ...

随机推荐

  1. BZOJ 3106 棋盘游戏

    Description 一个\(n \times n(n \le 2)\)棋盘上有黑白棋子各一枚.游戏者A和B轮流移动棋子,A先走. A的移动规则:只能移动白棋子.可以往上下左右四个方向之一移动一格. ...

  2. Java吸收换行符

            今天做题遇到的--         由于读入的字符串可能包含空格,所以采用nextLine. int n = sc.nextInt(); for(int i=0; i<n; i+ ...

  3. Cow Exhibition

    poj2184:http://poj.org/problem?id=2184 题意:给你n头牛,每头牛有一个S值和一个F值,现在的问题是,要你选出其中的一些牛求出S+T的最大值.但是要保证总的s> ...

  4. codeforces C. Inna and Huge Candy Matrix

    http://codeforces.com/problemset/problem/400/C 题意:给你一个n*m的矩阵,然后在矩阵中有p个糖果,给你每个糖果的初始位置,然后经过x次顺时针反转,y次旋 ...

  5. Java 8 中的 Streams API 详解

    为什么需要 Stream Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 ...

  6. 【Linux】鸟哥的Linux私房菜基础学习篇整理(二)

    1. dumpe2fs [-bh] devicename:查询superblock信息.参数:-b:列出保留为坏道的部分:-h:列出superblock的数据,不会列出其他的区段内容. 2. df [ ...

  7. 【模拟】Codeforces 671B Robin Hood

    题目链接: http://codeforces.com/problemset/problem/671/B 题目大意: N个人,每个人有Ci钱,现在有一个人劫富济贫,从最富的人之一拿走1元,再给最穷的人 ...

  8. 暴力求解——POJ 3134Power Calculus

    Description Starting with x and repeatedly multiplying by x, we can compute x31 with thirty multipli ...

  9. The Minimum Length - HUST 1010(求最小循环节)

    题意:有个一字符串A(本身不是循环串),然后经过很多次自增变成AAAAA,然后呢从自增串里面切出来一部分串B,用这个串B求出来A的长度.   分析:其实就是求最小循环节.......串的长度 - 最大 ...

  10. Appium移动自动化测试(一)--安装Appium(转)

    Appium移动自动化测试(一)--安装Appium 2015-05-30 17:48 by 虫师, 70668 阅读, 13 评论, 收藏, 编辑 Appium 自动化测试是很早之前就想学习和研究的 ...