前言
在遇到Android数据交互的状况时,思考过采取什么形式,在通过一段时间的学习,最终采取Okhttp这一个轻量级网络框架。
1、工具类实现
<code class="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
<code class="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中开启网络权限,才可能拜访到后盾数据
<code class="xml"><!-- 容许用户拜访网络,这一行要加在<manifest>的下一行 --> <uses-permission android:name="android.permission.INTERNET" />