Dowemo
0 0 0 0

And okhttp 's use would be familiar to everyone, and share the okhttp in our own project today.

Because of the project 's server framework, the request succeeded and the failure returned is different, the error code and error messages are returned only if okhttp return code isn't 200, so I'm encapsulated in the network framework layer to return the details back to the foreground to supply the next operation. 1. Fi & t: new callbac netinterface package, then create the interface and nettool, oktool.
2. Callback: Here we define our callback, and you can add methods to your own needs. According to these callbacks, we'll be able to use loadinglayout for the use of loadinlayout, please look at my article: 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 request and get request direct return to json data.There's a note in it.
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");//Jsonpublic 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请求@Overridepublic <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() {
 @Overridepublic 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() {
 @Overridepublic void onFailure(Call call, final IOException e) {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onError(e);}
 });}
 @Overridepublic 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() {
 @Overridepublic void run() {
 callBack.onSuccess(result);}
 });} catch (final Throwable e) {
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic 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请求@Overridepublic <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() {
 @Overridepublic 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() {
 @Overridepublic void onFailure(Call call, final IOException e) {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onError(e);}
 });}
 @Overridepublic 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() {
 @Overridepublic void run() {
 callBack.onSuccess(result);}
 });} catch (final Throwable e) {
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic 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请求@Overridepublic <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() {
 @Overridepublic 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() {
 @Overridepublic void onFailure(Call call, final IOException e) {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onError(e);}
 });}
 @Overridepublic 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() {
 @Overridepublic void run() {
 callBack.onSuccess(result);}
 });} catch (final Throwable e) {
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic 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请求@Overridepublic <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() {
 @Overridepublic 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() {
 @Overridepublic void onFailure(Call call, final IOException e) {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onError(e);}
 });}
 @Overridepublic 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() {
 @Overridepublic void run() {
 callBack.onSuccess(result);}
 });} catch (final Throwable e) {
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic 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数据@Overridepublic void jsonRequest(Context context, String url, Map<String, String> map, final CallBack<String> callBack) {
 //网络异常判断if (!Utils.checkNetworkAvailable(context)){
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic void onFailure(Call call, final IOException e) {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onError(e);}
 });}
 @Overridepublic void onResponse(Call call, Response response) throws IOException {
 final String str = response.body().string();//成功if (response.code() == 200) {
 try {
 mHandler.post(new Runnable() {
 @Overridepublic void run() {
 callBack.onSuccess(str);}
 });} catch (final Throwable e) {
 mHandler.post(new Runnable() {
 @Overridepublic 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() {
 @Overridepublic 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();}
 @Overridepublic <T> void postRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
 mInterface.postRequest(context,url,map,tClass,callBack);}
 @Overridepublic <T> void getRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
 mInterface.getRequest(context,url,map,tClass,callBack);}
 @Overridepublic <T> void putRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
 mInterface.putRequest(context,url,map,tClass,callBack);}
 @Overridepublic <T> void deleteRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
 mInterface.deleteRequest(context,url,map,tClass,callBack);}
 @Overridepublic void jsonRequest(Context context, String url, Map<String, String> map, CallBack<String> callBack) {
 mInterface.jsonRequest(context,url,map,callBack);}
}
6. Use:.
//Postprivate 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>() {
 //获取数据成功@Overridepublic void onSuccess(BeanLogin response) {
 Log.d("MainActivity","onSuccess:成功");//异常失败(后台数据库返回数据格式错误,无法映射成Bean)@Overridepublic void onError(Throwable e) {
 Log.d("MainActivity","onError:失败");}
 //请求数据失败(得到返回码和错误信息)@Overridepublic void onDefMessage(String code, String msg) {
 Log.d("MainActivity","onDefMessage_code:"+ code);Log.d("MainActivity","onDefMessage_msg:"+ msg);}
 //异常(网址错误等导致的404)@Overridepublic void onNotFound() {
 Log.d("MainActivity","onNotFound:url404");}
 @Overridepublic void onNoNet() {
 Log.d("MainActivity", "post网络异常");}
 });}

About checking network connectio &:
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;}
}











Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs