Android使用Okhttp进行数据交互

## 前言 >在遇到Android数据交互的情况时,思考过采取什么方式,在经过一段时间的学习,最终采取Okhttp这一个轻量级网络框架。 ## 1、工具类实现 ```java public class OkHttpUtil { public final static String TAG = "OkHttpUtil"; public final static int CONNECT_TIMEOUT = 60; public final static int READ_TIMEOUT = 100; public final static int WRITE_TIMEOUT = 60; // 后台数据接口基础路径 public final static String BASE_URL="http://192.168.64.1:8010"; public static final OkHttpClient client = new OkHttpClient.Builder() .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)// 设置读取超时时间 .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)// 设置写的超时时间 .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)// 设置连接超时时间 .build(); public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); //post请求,携带参数 public static String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } //get请求。不带参数 public static String get(String url) throws IOException{ Request request = new Request.Builder() .url(url) .get() .build(); Response response = null; //同步请求返回的是response对象 response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } } ``` ## 2、场景应用 举个栗子:商城app中首页中想要获取所有商品数据展示出来 后台用的是springboot,数据接口是:/api/commodity/getAllGoodByType ```java private void initProducts() { String url = OkHttpUtil.BASE_URL + "/api/commodity/getAllGoodByType"; // 主线程 new Thread(new Runnable() { @Override public void run() { try { String callStr = OkHttpUtil.get(url); JSONObject call_json = JSONObject.parseObject(callStr); final String code = call_json.getString("code"); final String msg = call_json.getString("msg"); if (code.equals("0")) { proList = JSON.parseObject(callStr, GoodsBean.class); //开启子线程,更新UI界面 hander.sendEmptyMessage(0); Looper.prepare(); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); Looper.loop(); } else if (code.equals("500")) { Looper.prepare(); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); Looper.loop(); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } //子线程通知主线程更新ui private Handler hander = new Handler(){ @Override public void handleMessage(Message msg) { switch(msg.what){ case 0: // notifyDataSetChanged动态更新UI proAd.notifyDataSetChanged(); proAd.add(proList.getData()); // 在适配器上添加数据 recommendRec.setAdapter(proAd); break; default: // do something break; } } }; ``` - 注意:在进行数据交互时,需要在android中开启网络权限,才能够访问到后台数据 ```xml ```
上一篇:使用OkHttp中的MockWebServer进行接口模拟测试


下一篇:Caffe训练AlexNet网络,精度不高或者为0的问题结果