依赖 依赖一定不要写错了 用的别的版本 可能封装的方法也就不一样了
compile 'com.squareup.okhttp3:okhttp:3.2.0'
BaseCallBack
package com.example.liuan.phonevideo.http;
import com.google.gson.internal.$Gson$Types;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Name: BaseCallBack
* Action:
* Author: liuan
* creatTime:2017-01-18 10:36
*/
public abstract class BaseCallBack<T> {
Type type;
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()
{
type = getSuperclassTypeParameter(getClass());
}
public abstract void onFailure(int code,Exception e);
public abstract void onSucess(T data);
}
HttpManager
package com.example.liuan.phonevideo.http;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Name: HttpManager
* Action:Http简单封装
* Author: liuan
* creatTime:2017-01-18 10:13
*/
public class HttpManager {
//懒汉式
private static HttpManager httpManager;
private Gson gson;
private Handler handler;
//不需要静态
private OkHttpClient okHttpClient;
private HttpManager() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
gson = new Gson();
//使用主线程Looper 初始化Handler
handler = new Handler(Looper.getMainLooper());
}
//返回单列对象
public static HttpManager getInstaance() {
if (httpManager == null) {
httpManager = new HttpManager();
}
return httpManager;
}
// public OkHttpClient getOkHttpClient() {
// return okHttpClient;
// }
public void doPost(String url, Map<String, String> params, BaseCallBack callBack) {
//发起Post请求
// System.out.println("doPost:url="+url);
//峰会组昂请求体内容
FormBody.Builder formBody = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
formBody.add(entry.getKey(), entry.getValue());
}
RequestBody body = formBody.build();
Request request = new Request.Builder().url(url).post(body).build();
doRequest(request, callBack);
}
//发起get请求
public void doGet(String url, BaseCallBack callBack) {
Request request = new Request.Builder()
.url(url).build();
doRequest(request, callBack);
}
private void doRequest(final Request request, final BaseCallBack baseCallBack) {
//打开浏览器
//ctrl+alt+v创建局部变量
//设置请求参数
//创建访问对象 相当于 打开标签页
Call call = okHttpClient.newCall(request);
//发起异步
call.enqueue(new Callback() {
//连接服务器失败
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
baseCallBack.onFailure(-1, e);
}
});
}
//成功获取到服务器数据 404,500之类的错误状态 也是获取到了数据
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String data = response.body().string();
//获取服务器数据
handler.post(new Runnable() {
@Override
public void run() {
if (response.isSuccessful()) {
// System.out.println("获取到数据数据" + response.body().string());
//界面想要直接获取String 字符串 不需要解析
if (String.class==baseCallBack.type){
//界面上想要直接获取String 字符串,不需要解析
baseCallBack.onSucess(data);
}else{
//默认解析 Bean
try {
Object json = gson.fromJson(data, baseCallBack.type);
baseCallBack.onSucess(json);
} catch (JsonSyntaxException e) {
e.printStackTrace();
baseCallBack.onFailure(-2,new RuntimeException("解析JSON出错:"+data));
}
}
} else{
baseCallBack.onFailure(response.code(), new RuntimeException("服务器返回错误码"+response.code()));}
}
});
}
});
}
}