安卓网络访问工具类
这个网络工具类,需要添加2个jar包。分别是okhttp和okio jar包。获取直接gradle进行构建下载 implementation 'com.squareup.okhttp3:okhttp:3.10.0' 关于更加复杂的使用。请参考如下文章:https://www.jianshu.com/p/da4a806e599b 本类的使用方法如下: 初始化,需要传入handler。用于网络获取数据后,返回数据用于UI操作。基本使用方法如下 private Handler handler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { switch (message.what){ case 1: Strubf result=httpUtils.getResult(); break; } return false; } }); HttpHelper httpUtils=new HttpHelper(handler); httpUtils.post(url,json,1); public class HttpHelper { private MediaType JSON=MediaType.parse("application/json;charset=utf-8"); private OkHttpClient client=new OkHttpClient(); private String result; private Handler handler; public HttpHelper(Handler handler) { this.handler = handler; } public String getResult() { return result; } public void post(String url,String json,final int code){ RequestBody body=RequestBody.create(JSON,json); final Request request=new Request.Builder() .url(url) .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { result=response.body().string(); handler.sendEmptyMessage(code); } }); } public void getPic(String url,final int code){ OkHttpClient okHttpClient=new OkHttpClient(); Request request=new Request.Builder() .url(url) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { InputStream inputStream=response.body().byteStream(); Bitmap bitmap= BitmapFactory.decodeStream(inputStream); Message msg=new Message(); msg.what=code; msg.obj=bitmap; handler.sendMessage(msg); } }); } }
一万年太久,只争朝夕!