一、Okhttp简介
Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然两者都支持
HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用
HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。
OkHttp是一个高效的HTTP库:
1.支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
2.如果SPDY不可用,则通过连接池来减少请求延时
3.无缝的支持GZIP来减少数据流量
4. 缓存响应数据来减少重复的网络请求
OkHttp会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,
会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您
用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。
二、Okhttp用法
1、Get 请求
OkHttpClient 客户端对象
Request是OkHttp中访问的请求,
Builder是辅助类。
Response即OkHttp中的响应。
2、Http POST (JSON)
MediaType 数据类型
RequestBody 请求数据
3、Http POST (FormData)
FormEncodingBuilder 表单构造器
三、Okhttp的简单封装
OkHttpHelper.java
public class OkHttpHelper {
public static final int TOKEN_MISSING=401;// token 丢失
public static final int TOKEN_ERROR=402; // token 错误
public static final int TOKEN_EXPIRE=403; // token 过期
public static final String TAG="OkHttpHelper";
private static OkHttpHelper mInstance;
private OkHttpClient mHttpClient;
private Gson mGson;
private Handler mHandler;
static {
mInstance = new OkHttpHelper();
}
private OkHttpHelper(){
mHttpClient = new OkHttpClient();
mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);
mGson = new Gson();
mHandler = new Handler(Looper.getMainLooper());
};
public static OkHttpHelper getInstance(){
return mInstance;
}
public void get(String url,Map<String,Object> param,BaseCallback callback){
Request request = buildGetRequest(url,param);
request(request,callback);
}
public void get(String url,BaseCallback callback){
get(url,null,callback);
}
public void post(String url,Map<String,Object> param, BaseCallback callback){
Request request = buildPostRequest(url,param);
request(request,callback);
}
public void request(final Request request,final BaseCallback callback){
callback.onBeforeRequest(request);
mHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
callbackFailure(callback, request, e);
}
@Override
public void onResponse(Response response) throws IOException {
// callback.onResponse(response);
callbackResponse(callback,response);
if(response.isSuccessful()) {
String resultStr = response.body().string();
Log.d(TAG, "result=" + resultStr);
if (callback.mType == String.class){
callbackSuccess(callback,response,resultStr);
}
else {
try {
Object obj = mGson.fromJson(resultStr, callback.mType);
callbackSuccess(callback,response,obj);
}
catch (com.google.gson.JsonParseException e){ // Json解析的错误
callback.onError(response,response.code(),e);
}
}
}
else if(response.code() == TOKEN_ERROR||response.code() == TOKEN_EXPIRE ||response.code() == TOKEN_MISSING ){
callbackTokenError(callback,response);
}
else {
callbackError(callback,response,null);
}
}
});
}
private void callbackTokenError(final BaseCallback callback , final Response response ){
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onTokenError(response,response.code());
}
});
}
private void callbackSuccess(final BaseCallback callback , final Response response, final Object obj ){
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(response, obj);
}
});
}
private void callbackError(final BaseCallback callback , final Response response, final Exception e ){
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(response,response.code(),e);
}
});
}
private void callbackFailure(final BaseCallback callback , final Request request, final IOException e ){
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onFailure(request,e);
}
});
}
private void callbackResponse(final BaseCallback callback , final Response response ){
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onResponse(response);
}
});
}
private Request buildPostRequest(String url,Map<String,Object> params){
return buildRequest(url,HttpMethodType.POST,params);
}
private Request buildGetRequest(String url,Map<String,Object> param){
return buildRequest(url,HttpMethodType.GET,param);
}
private Request buildRequest(String url,HttpMethodType methodType,Map<String,Object> params){
Request.Builder builder = new Request.Builder()
.url(url);
if (methodType == HttpMethodType.POST){
RequestBody body = builderFormData(params);
builder.post(body);
}
else if(methodType == HttpMethodType.GET){
url = buildUrlParams(url,params);
builder.url(url);
builder.get();
}
return builder.build();
}
private String buildUrlParams(String url ,Map<String,Object> params) {
if(params == null)
params = new HashMap<>(1);
String token = CniaoApplication.getInstance().getToken();
if(!TextUtils.isEmpty(token))
params.put("token",token);
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey() + "=" + (entry.getValue()==null?"":entry.getValue().toString()));
sb.append("&");
}
String s = sb.toString();
if (s.endsWith("&")) {
s = s.substring(0, s.length() - 1);
}
if(url.indexOf("?")>0){
url = url +"&"+s;
}else{
url = url +"?"+s;
}
return url;
}
private RequestBody builderFormData(Map<String,Object> params){
FormEncodingBuilder builder = new FormEncodingBuilder();
if(params !=null){
for (Map.Entry<String,Object> entry :params.entrySet() ){
builder.add(entry.getKey(),entry.getValue()==null?"":entry.getValue().toString());
}
String token = CniaoApplication.getInstance().getToken();
if(!TextUtils.isEmpty(token))
builder.add("token", token);
}
return builder.build();
}
enum HttpMethodType{
GET,
POST,
}
}
BaseCallback.java
public abstract class BaseCallback <T> {
public Type mType;
static Type getSuperclassTypeParameter(Class<?> subclass)
{
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class)
{
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
public BaseCallback()
{
mType = getSuperclassTypeParameter(getClass());
}
public abstract void onBeforeRequest(Request request);
public abstract void onFailure(Request request, Exception e) ;
/**
*请求成功时调用此方法
* @param response
*/
public abstract void onResponse(Response response);
/**
*
* 状态码大于200,小于300 时调用此方法
* @param response
* @param t
* @throws IOException
*/
public abstract void onSuccess(Response response,T t) ;
/**
* 状态码400,404,403,500等时调用此方法
* @param response
* @param code
* @param e
*/
public abstract void onError(Response response, int code,Exception e) ;
/**
* Token 验证失败。状态码401,402,403 等时调用此方法
* @param response
* @param code
*/
public abstract void onTokenError(Response response, int code);
}
SimpleCallback.java(处理Token的CallBack)
public abstract class SimpleCallback<T> extends BaseCallback<T> {
protected Context mContext;
public SimpleCallback(Context context){
mContext = context;
}
@Override
public void onBeforeRequest(Request request) {
}
@Override
public void onFailure(Request request, Exception e) {
}
@Override
public void onResponse(Response response) {
}
@Override
public void onTokenError(Response response, int code) {
ToastUtils.show(mContext, mContext.getString(R.string.token_error));
Intent intent = new Intent();
intent.setClass(mContext, LoginActivity.class);
mContext.startActivity(intent);
mApplication.getInstance().clearUser();
}
}
SpotsCallBack.java(包含加载框的CallBack)
public abstract class SpotsCallBack<T> extends SimpleCallback<T> {
private SpotsDialog mDialog;
public SpotsCallBack(Context context){
super(context);
initSpotsDialog();
}
private void initSpotsDialog(){
mDialog = new SpotsDialog(mContext,"拼命加载中...");
}
public void showDialog(){
mDialog.show();
}
public void dismissDialog(){
mDialog.dismiss();
}
public void setLoadMessage(int resId){
mDialog.setMessage(mContext.getString(resId));
}
@Override
public void onBeforeRequest(Request request) {
showDialog();
}
@Override
public void onResponse(Response response) {
dismissDialog();
}
}