OKHttp的使用想起来大家都很熟悉了,今天分享一下我们自己的项目中封装的OKHttp。
因为项目的服务器框架中,请求成功和失败的返回是不一样的,错误码和错误信息,只有在OKHttp返回码不是200的情况下才返回,所以,我在网络框架层中进行了封装,将其中的细节返回到前台,以供给下一次操作。
1.首先:新建 net 包,再创建接口 CallBac NetInterface和类 NetTool,OKTool。
2.CallBacK:这里定义了我们的回调,大家可以根据自己的需求自己添加方法。
根据这些回调,我们这好可以使用到LoadingLayout,关于loadinLayout的使用,请看我的这篇文章: http://blog.csdn.net/eueheuen/article/details/77163390
public interface CallBack<T> {
//请求成功,数据正确,根据Bean返回我们的数据
void onSuccess(T response);
//请求成功后,数据回调失败,返回异常对象和异常信息
void onError(Throwable e);
//当错误信息返回在非200情况下(返回错误码和错误信息)
void onDefMessage(String code,String msg);
//网络404的情况(并不是没有网络)
void onNotFound();
//无网络的情况
void onNoNet();
}
3.NetInterface
public interface NetInterface {
//Post请求
<
T>
void postRequest(Context context
, String url
, Map<String
,String> map
,Class<
T> tClass
,CallBack<
T>callBack)
;
//Get请求
<
T>
void getRequest(Context context
, String url
, Map<String
,String> map
,Class<
T> tClass
,CallBack<
T>callBack)
;
//Put请求
<
T>
void putRequest(Context context
, String url
, Map<String
,String> map
,Class<T> tClass
,CallBack<T>callBack)
;
//Delete请求
<
T>
void deleteRequest(Context context
, String url
, Map<String
,String> map
,Class<T> tClass
,CallBack<T>callBack)
;
//Get直接返回Json数据
void jsonRequest(Context context
,String url
,Map<String
,String> map
,CallBack<String> callBack)
;
}
4.OKTool: 有 get post delete put 请求 和 Get请求直接返回 json 数据
具体的里面都有注释
public class OKTool
implements NetInterface {
private OkHttpClient
mOKHttpClient;
private Handler
mHandler =
new Handler(Looper.
getMainLooper())
;
private Gson
mGson;
//数据传输格式
public static final MediaType
JSON = MediaType.
parse(
"application/json; charset=utf-8")
;//Json
public static final MediaType
TEXT = MediaType.
parse(
"application/x-www-form-urlencoded; charset=utf-8")
;//文本
private static final MediaType
MEDIA_TYPE_JPEG = MediaType.
parse(
"image/jpeg")
;//图片
public OKTool(){
//初始化
mGson =
new Gson()
;
//进行超时时间及缓存大小配置
mOKHttpClient =
new OkHttpClient.Builder()
.retryOnConnectionFailure(
true)
.connectTimeout(
5, TimeUnit.
SECONDS)
.cache(
new Cache(Environment.
getExternalStorageDirectory()
, 10 *
1024 *
1024))
.build()
;
}
//Post请求
@Override
public <
T>
void postRequest(
final Context context
, String url
, Map<String
, String> map
, final Class<
T> tClass
, final CallBack<
T> callBack) {
//网络异常判断
if (!Utils.
checkNetworkAvailable(context)){
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onNoNet()
;
}
})
;
return;
}
String text =
"";
String key
,value
;
//发送Json数据
//final String jsonStr = mGson.toJson(map);
//向服务器不发送json 发送 文本
if (map!=
null) {
for (Map.Entry<String
, String> entry : map.entrySet()) {
key = entry.getKey()
;
value = entry.getValue()
;
text = text +
"&" + (key +
"=" + value)
;
}
}
RequestBody requestBody = RequestBody.
create(
TEXT,text)
;
final Request request =
new Request.Builder().url(url)
.post(requestBody)
//Header头根据具体项目的规定去添加
.addHeader(
"AID","20170630062508d2ib32lBty95o5RS")
.addHeader(
"APIVER","v1.0")
.addHeader(
"ACCEPT","application/json")
.build()
;
mOKHttpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call
, final IOException e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
@Override
public void onResponse(Call call
, Response response)
throws IOException {
String str = response.body().string()
;
final T result
;
//成功
if (response.code() ==
200) {
try {
result =
mGson.fromJson(str
, tClass)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onSuccess(
result)
;
}
})
;
}
catch (
final Throwable e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
//网址404的情况
}
else if (response.code() ==
404){
callBack.onNotFound()
;
}
//返回错误信息的情况
else {
JSONObject jsonObject =
null;
try {
jsonObject =
new JSONObject(str)
;
//msg和error_code根据具体的接口返回变动
final String msg = jsonObject.getString(
"msg")
;
final String errorCode = jsonObject.getString(
"error_code")
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onDefMessage(
errorCode,msg)
;
if ((
"2002").equals(
errorCode)||(
"2001").equals(
errorCode)){
//项目中设计到Token过期重新登陆,Token过期未 2002 2001
// Utils.ShowTokenNewLogin(context);
}
else {
//将错误信息返回到前端
callBack.onDefMessage(
errorCode,msg)
;
}
}
})
;
}
catch (JSONException e) {
e.printStackTrace()
;
}
}
}
})
;
}
//Get请求
@Override
public <
T>
void getRequest(Context context
, String url
, Map<String
, String> map
, final Class<
T> tClass
, final CallBack<
T> callBack) {
//网络异常判断
if (!Utils.
checkNetworkAvailable(context)){
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onNoNet()
;
}
})
;
return;
}
String text =
"";
String key
,value
;
//发送Json数据
//final String jsonStr = mGson.toJson(map);
//整理url数据
if (map!=
null) {
for (Map.Entry<String
, String> entry : map.entrySet()) {
key = entry.getKey()
;
value = entry.getValue()
;
text = text +
"&" + (key +
"=" + value)
;
}
}
if (text.length()>
0){
text = text.substring(
1,text.length())
;
url= url+
"?"+text
;
}
final Request request =
new Request.Builder().url(url)
.get()
.addHeader(
"AID","20170630062508d2ib32lBty95o5RS")
.addHeader(
"APIVER","v1.0")
.addHeader(
"ACCEPT","application/json")
.build()
;
mOKHttpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call
, final IOException e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
@Override
public void onResponse(Call call
, Response response)
throws IOException {
String str = response.body().string()
;
final T result
;
//成功
if (response.code() ==
200) {
try {
result =
mGson.fromJson(str
, tClass)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onSuccess(
result)
;
}
})
;
}
catch (
final Throwable e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
//网址404的情况
}
else if (response.code() ==
404){
callBack.onNotFound()
;
}
//返回错误信息的情况
else {
JSONObject jsonObject =
null;
try {
jsonObject =
new JSONObject(str)
;
final String msg = jsonObject.getString(
"msg")
;
final String errorCode = jsonObject.getString(
"error_code")
;
Log.
d(
"NewOkTool", msg)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onDefMessage(
errorCode,msg)
;
// if (("2002").equals(errorCode)||("2001").equals(errorCode)){
// Utils.ShowTokenNewLogin(context);
// }else {
// callBack.onDefMessage(errorCode,msg);
// }
}
})
;
}
catch (JSONException e) {
e.printStackTrace()
;
}
}
}
})
;
}
//Put请求
@Override
public <
T>
void putRequest(Context context
, String url
, Map<String
, String> map
, final Class<
T> tClass
, final CallBack<
T> callBack) {
//网络异常判断
if (!Utils.
checkNetworkAvailable(context)){
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onNoNet()
;
}
})
;
return;
}
String text =
"1";
String key
,value
;
//发送Json数据
//final String jsonStr = mGson.toJson(map);
//向服务器不发送json 发送 文本
if (map!=
null) {
for (Map.Entry<String
, String> entry : map.entrySet()) {
key = entry.getKey()
;
value = entry.getValue()
;
text = text +
"&" + (key +
"=" + value)
;
}
}
RequestBody requestBody = RequestBody.
create(
TEXT,text)
;
final Request request =
new Request.Builder().url(url)
.put(requestBody)
.addHeader(
"AID","20170630062508d2ib32lBty95o5RS")
.addHeader(
"APIVER","v1.0")
.addHeader(
"ACCEPT","application/json")
.build()
;
mOKHttpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call
, final IOException e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
@Override
public void onResponse(Call call
, Response response)
throws IOException {
String str = response.body().string()
;
final T result
;
//成功
if (response.code() ==
200) {
try {
result =
mGson.fromJson(str
, tClass)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onSuccess(
result)
;
}
})
;
}
catch (
final Throwable e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
//网址404的情况
}
else if (response.code() ==
404){
callBack.onNotFound()
;
}
//返回错误信息的情况
else {
JSONObject jsonObject =
null;
try {
jsonObject =
new JSONObject(str)
;
final String msg = jsonObject.getString(
"msg")
;
final String errorCode = jsonObject.getString(
"error_code")
;
Log.
d(
"NewOkTool", msg)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onDefMessage(
errorCode,msg)
;
// if (("2002").equals(errorCode)||("2001").equals(errorCode)){
// Utils.ShowTokenNewLogin(context);
// }else {
// callBack.onDefMessage(errorCode,msg);
// }
}
})
;
}
catch (JSONException e) {
e.printStackTrace()
;
}
}
}
})
;
}
//Delete请求
@Override
public <
T>
void deleteRequest(Context context
, String url
, Map<String
, String> map
, final Class<
T> tClass
, final CallBack<
T> callBack) {
//网络异常判断
if (!Utils.
checkNetworkAvailable(context)){
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onNoNet()
;
}
})
;
return;
}
String text =
"1";
String key
,value
;
//发送Json数据
//final String jsonStr = mGson.toJson(map);
//向服务器不发送json 发送 文本
if (map!=
null) {
for (Map.Entry<String
, String> entry : map.entrySet()) {
key = entry.getKey()
;
value = entry.getValue()
;
text = text +
"&" + (key +
"=" + value)
;
}
}
RequestBody requestBody = RequestBody.
create(
TEXT,text)
;
final Request request =
new Request.Builder().url(url)
.delete(requestBody)
.addHeader(
"AID","20170630062508d2ib32lBty95o5RS")
.addHeader(
"APIVER","v1.0")
.addHeader(
"ACCEPT","application/json")
.build()
;
mOKHttpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call
, final IOException e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
@Override
public void onResponse(Call call
, Response response)
throws IOException {
String str = response.body().string()
;
final T result
;
//成功
if (response.code() ==
200) {
try {
result =
mGson.fromJson(str
, tClass)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onSuccess(
result)
;
}
})
;
}
catch (
final Throwable e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
//网址404的情况
}
else if (response.code() ==
404){
callBack.onNotFound()
;
}
//返回错误信息的情况
else {
JSONObject jsonObject =
null;
try {
jsonObject =
new JSONObject(str)
;
final String msg = jsonObject.getString(
"msg")
;
final String errorCode = jsonObject.getString(
"error_code")
;
Log.
d(
"NewOkTool", msg)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onDefMessage(
errorCode,msg)
;
// if (("2002").equals(errorCode)||("2001").equals(errorCode)){
// Utils.ShowTokenNewLogin(context);
// }else {
// callBack.onDefMessage(errorCode,msg);
// }
}
})
;
}
catch (JSONException e) {
e.printStackTrace()
;
}
}
}
})
;
}
//直接返回Json数据
@Override
public void jsonRequest(Context context
, String url
, Map<String
, String> map
, final CallBack<String> callBack) {
//网络异常判断
if (!Utils.
checkNetworkAvailable(context)){
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onNoNet()
;
}
})
;
return;
}
String text =
"";
String key
,value
;
//整理url数据
if (map!=
null) {
for (Map.Entry<String
, String> entry : map.entrySet()) {
key = entry.getKey()
;
value = entry.getValue()
;
text = text +
"&" + (key +
"=" + value)
;
}
}
if (text.length()>
0){
text = text.substring(
1,text.length())
;
url= url+
"?"+text
;
}
final Request request =
new Request.Builder().url(url)
.get()
.addHeader(
"AID","20170630062508d2ib32lBty95o5RS")
.addHeader(
"APIVER","v1.0")
.addHeader(
"ACCEPT","application/json")
.build()
;
mOKHttpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call
, final IOException e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
@Override
public void onResponse(Call call
, Response response)
throws IOException {
final String str = response.body().string()
;
//成功
if (response.code() ==
200) {
try {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onSuccess(
str)
;
}
})
;
}
catch (
final Throwable e) {
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onError(
e)
;
}
})
;
}
//网址404的情况
}
else if (response.code() ==
404){
callBack.onNotFound()
;
}
//返回错误信息的情况
else {
JSONObject jsonObject =
null;
try {
jsonObject =
new JSONObject(str)
;
final String msg = jsonObject.getString(
"msg")
;
final String errorCode = jsonObject.getString(
"error_code")
;
Log.
d(
"NewOkTool", msg)
;
mHandler.post(
new Runnable() {
@Override
public void run() {
callBack.onDefMessage(
errorCode,msg)
;
// if (("2002").equals(errorCode)||("2001").equals(errorCode)){
// Utils.ShowTokenNewLogin(context);
// }else {
// callBack.onDefMessage(errorCode,msg);
// }
}
})
;
}
catch (JSONException e) {
e.printStackTrace()
;
}
}
}
})
;
}
} 5.NetTool:
public class NetTool
implements NetInterface {
private static NetTool
sNetTool;
private NetInterface
mInterface;
//双重校验锁(单例)
public static NetTool
getInstance(){
if (
sNetTool ==
null){
synchronized (NetTool.
class){
if (
sNetTool ==
null){
sNetTool =
new NetTool()
;
}
}
}
return sNetTool;
}
private NetTool(){
mInterface =
new OKTool()
;
}
@Override
public <
T>
void postRequest(Context context
, String url
, Map<String
, String> map
, Class<
T> tClass
, CallBack<
T> callBack) {
mInterface.postRequest(context
,url
,map
,tClass
,callBack)
;
}
@Override
public <
T>
void getRequest(Context context
, String url
, Map<String
, String> map
, Class<
T> tClass
, CallBack<
T> callBack) {
mInterface.getRequest(context
,url
,map
,tClass
,callBack)
;
}
@Override
public <
T>
void putRequest(Context context
, String url
, Map<String
, String> map
, Class<
T> tClass
, CallBack<
T> callBack) {
mInterface.putRequest(context
,url
,map
,tClass
,callBack)
;
}
@Override
public <
T>
void deleteRequest(Context context
, String url
, Map<String
, String> map
, Class<
T> tClass
, CallBack<
T> callBack) {
mInterface.deleteRequest(context
,url
,map
,tClass
,callBack)
;
}
@Override
public void jsonRequest(Context context
, String url
, Map<String
, String> map
, CallBack<String> callBack) {
mInterface.jsonRequest(context
,url
,map
,callBack)
;
}
}
6.使用:
//Post
private void login() {
String url =
"http://ig.indata3.com/mice-api/user/company/login";
String urlBad =
"http://indata3.com/mice-api/user/company/login";
HashMap map =
new HashMap()
;
map.put(
"mobilephone","18510063463")
;
map.put(
"user_pwd","123")
;
map.put(
"state_code","+86")
;
NetTool.
getInstance().postRequest(
this, url
, map
, BeanLogin.
class, new CallBack<BeanLogin>() {
//获取数据成功
@Override
public void onSuccess(BeanLogin response) {
Log.
d(
"MainActivity","onSuccess:成功")
;
//异常失败(后台数据库返回数据格式错误,无法映射成Bean)
@Override
public void onError(Throwable e) {
Log.
d(
"MainActivity","onError:失败")
;
}
//请求数据失败(得到返回码和错误信息)
@Override
public void onDefMessage(String code
, String msg) {
Log.
d(
"MainActivity","onDefMessage_code:"+ code)
;
Log.
d(
"MainActivity","onDefMessage_msg:"+ msg)
;
}
//异常(网址错误等导致的404)
@Override
public void onNotFound() {
Log.
d(
"MainActivity","onNotFound:url404")
;
}
@Override
public void onNoNet() {
Log.
d(
"MainActivity", "post网络异常")
;
}
})
;
}
关于检查网络连接:
public class Utils {
//判断网络状态
public static boolean checkNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
NetworkInfo netWorkInfo = info[i];
if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
}
}
}
return false;
}
}