okhttp 简单用法
1.gradle 依赖 github 中查找最新的
2.MyApplication oncreate 中:
@Override public void onCreate () { super.onCreate(); myApplication = this; mHttpClient = new OkHttpClient(); }
2.封装执行方法
public Response excuteHttp(String url){ try { Request build = new Request.Builder().url(url).build(); Response execute = mHttpClient.newCall(build).execute(); return execute; } catch (IOException e) { return null; // e.printStackTrace(); } }
3.子线程中调用:
private void downloadFile () { final String url = "http://192.168.1.151:8080/pic/beautiful4.jpg"; new Thread(new Runnable() { @Override public void run () { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } MyApplication instance = MyApplication.getInstance(); Response response = instance.excuteHttp(url); if(response==null){ Log.e(TAG,"OKHTTP RESPONSE 是null"); }else{ ResponseBody body = response.body(); InputStream inputStream = body.byteStream(); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); Log.e(TAG,"OKHTTP RESPONSE 不为null"); runOnUiThread(new Runnable() { @Override public void run () { mImageView.setImageBitmap(bitmap); } }); } } }).start(); }