首先在build.gradle添加依赖
compile 'com.yanzhenjie.nohttp:okhttp:1.1.1' compile 'com.google.code.gson:gson:2.8.0' //这个我用于解析json数据
使用之前在application中初始化 application记得在andoridMainfest.xml中注册
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); NoHttp.initialize(this, new NoHttp.Config() .setConnectTimeout(30 * 1000) // 全局连接超时时间,单位毫秒。 .setReadTimeout(30 * 1000) // 全局服务器响应超时时间,单位毫秒。 .setCacheStore(new DiskCacheStore(this) ) // 配置缓存到SD卡。) .setCookieStore( new DBCookieStore(this) .setEnable(false) // true启用自动维护Cookie,fasle禁用自动维护Cookie。 ) .setNetworkExecutor(new OkHttpNetworkExecutor()) // 使用OkHttp做网络层。 ); Logger.setDebug(true); // 开启NoHttp调试模式。 Logger.setTag("NoHttpSample"); // 设置NoHttp打印Log的TAG。 } }
//开始使用
public Presenter(){ String url="http://www.weather.com.cn/data/cityinfo/101010100.html"; RequestQueue requestQueue = NoHttp.newRequestQueue(); // 如果要指定并发值,传入数字即可:NoHttp.newRequestQueue(3); Request<JSONObject> request = NoHttp.createJsonObjectRequest(url); // 发起请求 requestQueue.add(0, request, new ResponseListener()); }
//数据请求完回调结果
class ResponseListener implements OnResponseListener { @Override public void onStart(int what) { } @Override public void onSucceed(int what, Response response) { if(response.isSucceed()){ JSONObject o = (JSONObject) response.get(); String s = o.toString(); Gson gson = new Gson(); Mode mode = gson.fromJson(s,Mode.class); Mode.WeatherinfoBean weatherinfo = mode.getWeatherinfo(); Logger.e(weatherinfo.city); Logger.e(weatherinfo.cityid); Logger.e(weatherinfo.img1); Logger.e(weatherinfo.img2); Logger.e(weatherinfo.ptime); Logger.e(weatherinfo.temp2); /* 输出结果 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: 北京 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: 101010100 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: n0.gif 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: d0.gif 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: 18:00 04-09 06:43:23.133 25022-25022/com.cloud.nohttpdemo E/NoHttpSample: 16℃*/ } } @Override public void onFailed(int what, Response response) { } @Override public void onFinish(int what) { } } }
noHttp参考文档 http://doc.nohttp.net/222384