Android使用Okhttp进行数据交互

  • Post author:
  • Post category:其他




前言

在遇到Android数据交互的情况时,思考过采取什么方式,在经过一段时间的学习,最终采取Okhttp这一个轻量级网络框架。



1、工具类实现

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

	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中开启网络权限,才能够访问到后台数据

    <!-- 允许用户访问网络,这一行要加在<manifest>的下一行 -->
    <uses-permission android:name="android.permission.INTERNET" />
    



版权声明:本文为DevelopmentStack原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。