使用场景:
联网
在App的build.gradle中添加引用:
//网络框架 compile 'com.yanzhenjie.nohttp:nohttp:1.1.1'
在application中重写,并且声明nohttp
package itcast.zz.kdniaodemo; import android.app.Application; import com.yanzhenjie.nohttp.Logger; import com.yanzhenjie.nohttp.NoHttp; /** * Created by SensYang on 2017/05/23 10:16 */ public class MZApplication extends Application { private static MZApplication instance; @Override public void onCreate() { super.onCreate(); NoHttp.initialize(this); Logger.setDebug(true); // 开启NoHttp调试模式。 Logger.setTag("Omi_NoHttp--->"); // 设置NoHttp打印Log的TAG。 } public static MZApplication getInstance(){ if (instance == null) { instance = new MZApplication(); } return instance; } }
在清单文件中添加这个application的使用
package itcast.zz.kdniaodemo; import android.app.Application; import com.yanzhenjie.nohttp.Logger; import com.yanzhenjie.nohttp.NoHttp; /** * Created by SensYang on 2017/05/23 10:16 */ public class MZApplication extends Application { private static MZApplication instance; @Override public void onCreate() { super.onCreate(); NoHttp.initialize(this); Logger.setDebug(true); // 开启NoHttp调试模式。 Logger.setTag("Omi_NoHttp--->"); // 设置NoHttp打印Log的TAG。 } public static MZApplication getInstance(){ if (instance == null) { instance = new MZApplication(); } return instance; } }
1 创建请求父类:
package itcast.zz.kdniaodemo; import android.os.Environment; import com.yanzhenjie.nohttp.Binary; import com.yanzhenjie.nohttp.Headers; import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.download.DownloadRequest; import com.yanzhenjie.nohttp.rest.RestRequest; import com.yanzhenjie.nohttp.rest.StringRequest; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; /** * Created by SensYang on 2017/03/14 10:10 */ public class BaseBeanRequest<T> extends RestRequest<T> { private Class<T> beanClass; private String data; private static final String CancelSign = "CancelSign"; public BaseBeanRequest(Class<T> beanClass, String url) { this(beanClass, url, RequestMethod.GET); } public BaseBeanRequest(Class<T> beanClass, String url, RequestMethod requestMethod) { this(url, beanClass, url, requestMethod); } public BaseBeanRequest(Object sign, Class<T> beanClass, String url) { this(sign, beanClass, url, RequestMethod.GET); } public BaseBeanRequest(Object sign, Class<T> beanClass, String url, RequestMethod requestMethod) { super(url, requestMethod); this.beanClass = beanClass; setCancelSign(sign); // if (url.startsWith(HttpConfig.MAIN_HOST)) { // setSSLSocketFactory(SSLHelper.getDoubleSSLCertifcation()); // setHostnameVerifier(SSLHelper.verifier); // } if (requestMethod == RequestMethod.POST && url.endsWith(".php")) { setContentType("application/x-www-form-urlencoded"); } } /** public static DownloadRequest createDownloadRequest(String url, String fileFolder, boolean isDeleteOld) { return createDownloadRequest(url, RequestMethod.GET, fileFolder, isDeleteOld); } */ @Override public T parseResponse(Headers responseHeaders, byte[] responseBody) throws Exception { String result = StringRequest.parseResponseString(responseHeaders, responseBody); return JsonUtils.parserJson2Bean(result, beanClass); } public String getData() { return data; } public void setData(String data) { this.data = data; } public final void addParam(Object param) { try { Field[] fields = param.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(param); if (value != null) { if (value instanceof Integer) { add(field.getName(), (Integer) value); } else if (value instanceof Long) { add(field.getName(), (Long) value); } else if (value instanceof Boolean) { add(field.getName(), (Boolean) value); } else if (value instanceof Character) { add(field.getName(), (Character) value); } else if (value instanceof Double) { add(field.getName(), (Double) value); } else if (value instanceof Float) { add(field.getName(), (Float) value); } else if (value instanceof Short) { add(field.getName(), (Short) value); } else if (value instanceof Byte) { add(field.getName(), (Byte) value); } else if (value instanceof String) { add(field.getName(), (String) value); } else if (value instanceof Binary) { add(field.getName(), (Binary) value); } else if (value instanceof File) { String fileName = ((File) value).getName(); addHeader(Headers.HEAD_KEY_CONTENT_DISPOSITION, "form-data;name=\"" + fileName + "\";fileName=\"" + fileName + "\""); add(field.getName(), (File) value); } } } } catch (IllegalAccessException e) { e.printStackTrace(); } } @Override public void onWriteRequestBody(OutputStream writer) throws IOException { if (data != null) { byte[] stringData = data.getBytes(); setHeader(Headers.HEAD_KEY_CONTENT_LENGTH, String.valueOf(stringData.length)); writer.write(stringData); writer.flush(); } super.onWriteRequestBody(writer); } public DownloadRequest getDownRequest(Object sign, String url,String filename) { setCancelSign(sign); //TODO 设计https联网 // if (url.startsWith(HttpConfig.MAIN_HOST)) { // setSSLSocketFactory(SSLHelper.getDoubleSSLCertifcation()); // setHostnameVerifier(SSLHelper.verifier); // } if (url.endsWith(".php")) { setContentType("application/x-www-form-urlencoded"); } DownloadRequest downloadRequest = NoHttp.createDownloadRequest(url, Environment.getExternalStorageDirectory().getPath(), filename, true, false); downloadRequest.setCancelSign(CancelSign); return downloadRequest; } }
2 创建请求对象:
package itcast.zz.kdniaodemo; import com.yanzhenjie.nohttp.RequestMethod; /** * Created by SensYang on 2017/05/23 9:56 */ public class MZRequest<T> extends BaseBeanRequest<T> { public MZRequest(Class<T> beanClass, String url) { this(beanClass, url,RequestMethod.GET); } public MZRequest(Class<T> beanClass, String url, RequestMethod requestMethod){ this(null,beanClass,url,requestMethod); } /** *在这里可以将联网单独整理成一个类出来,将完整的网址在这里组合 */ public MZRequest(Object sign,Class<T> beanClass,String url,RequestMethod requestMethod){ super(sign,beanClass,url,requestMethod); } }
3 创建NohttpUtil
package itcast.zz.kdniaodemo; import android.util.Log; import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.rest.OnResponseListener; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.RequestQueue; import com.yanzhenjie.nohttp.tools.NetUtil; /** * Created by SensYang on 2017/05/23 10:06 */ public class NoHttpUtil { private RequestQueue requestQueue; private static NoHttpUtil instance; public static NoHttpUtil getInstance(){ if (instance == null) { instance = new NoHttpUtil(); } return instance; } public <T> void add(Request<T> request){ add(-1,request);} public <T> void add(int what,Request<T> requeat){ add(what,requeat,null);} public <T> void add(Request<T> request,OnResponseListener<T> onResponseListener){ add(-1,request,onResponseListener); } public <T> void add(int what, Request<T> request, OnResponseListener<T> onResponseListener){ if (NetUtil.isNetworkAvailable()) requestQueue.add(what,request,onResponseListener); else Log.e("log","当前没有可用网络"); } private NoHttpUtil(){ requestQueue = NoHttp.newRequestQueue(3);} private void cancle(Object sign){ requestQueue.cancelBySign(sign);} }
4 创建BeanJson类:
package com.omi.bean.base; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import java.util.List; /** * Created by SensYang on 2017/04/03 18:46 */ @JsonIgnoreProperties(ignoreUnknown = true)//添加一些忽略 public class BaseJson<T> { private String result; private String type; private String msg; private List<T> userinfo; private List<T> datalist; private T data; private String resultCode; private String resultText; //快递鸟返回json串特有 private String EBusinessID; private String LogisticCode; private String ShipperCode; private String State; private boolean Success; private List<T> Traces; public String getEBusinessID() { return EBusinessID; } public void setEBusinessID(String EBusinessID) { this.EBusinessID = EBusinessID; } public String getLogisticCode() { return LogisticCode; } public void setLogisticCode(String logisticCode) { LogisticCode = logisticCode; } public String getShipperCode() { return ShipperCode; } public void setShipperCode(String shipperCode) { ShipperCode = shipperCode; } public String getState() { return State; } public void setState(String state) { State = state; } public boolean isSuccess() { return Success; } public void setSuccess(boolean success) { Success = success; } public List<T> getTraces() { return Traces; } public void setTraces(List<T> traces) { Traces = traces; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<T> getUserinfo() { return userinfo; } public void setUserinfo(List<T> userinfo) { this.userinfo = userinfo; } public List<T> getDatalist() { return datalist; } public void setDatalist(List<T> datalist) { this.datalist = datalist; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getResultText() { return resultText; } public void setResultText(String resultText) { this.resultText = resultText; } }
联网实例:
/** * 获取收货地址列表 */ public void getShouHuoLocations(ResponseCallback callback){ OMiBeanRequest request = new OMiBeanRequest(LocationShouhuo.class, HttpConfig.URL_GET_SHOP_LOCATION_LIST, RequestMethod.GET); request.add("member_name",getPhone()); NoHttpUtil.getInstance().add(request, callback); }
当然,可以单独创建一个管理网址的类: HttpConfig,修改网址的时候也方便
https://gitee.com/longlyblack/jingshuainohttp