Android Response返回JSON数据到前台页面 多种主流方案

一、前言

本文介绍提交或请求Json数据的两种方式

方案一 使用postman,apifox或者 apiPost代码自动生成

如果你看了我想你一定会惊呆,代码是搬的不是写的

第一步 下载任意一种工具 请求body选择JSON形式

在这里插入图片描述

第二步 点击右侧</>符号按钮,选择生成语言为http或者okhttp

在这里插入图片描述

第三步 复制到你代码组装出一个方法即可,傻瓜式操作,且无bug

在这里插入图片描述

Android Java okhttp框架

需要在Gradle中自行添加对应框架的依赖

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
  .url("127.0.0.1:8081/v1/api/role/list")
  .method("GET", body)
  .addHeader("Content-Type", "application/json")
  .addHeader("authorization", "cloudCIA eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXIiOiJhZG1pbiIsInBhc3N3b3JkIjoiZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2UiLCJ0eXBlIjoxfSwiZXhwIjoxNTYwMzI4MjU3NTk1LCJpYXQiOjE1NjAyNDE4NTd9.frx6zMf2UCVYLbPeMcAy4fVZZSFzRl2v_yi7Wb97Q5Q")
  .build();
Response response = client.newCall(request).execute();

原生HTTP

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://127.0.0.1:8081/v1/api/role/list"))
    .header("content-type", "application/json")
    .method("GET", HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

JAVA unireset框架

HttpResponse<String> response = Unirest.get("http://127.0.0.1:8081/v1/api/role/list")
  .header("content-type", "application/json")
  .asString();

Android Kotlin okhttp框架

val client = OkHttpClient()

val request = Request.Builder()
  .url("http://127.0.0.1:8081/v1/api/role/list")
  .get()
  .addHeader("content-type", "application/json")
  .build()

val response = client.newCall(request).execute()

Java Asynchttp 框架

AsyncHttpClient client = new DefaultAsyncHttpClient();
client.prepare("GET", "http://127.0.0.1:8081/v1/api/role/list")
  .setHeader("content-type", "application/json")
  .execute()
  .toCompletableFuture()
  .thenAccept(System.out::println)
  .join();

client.close();

方案二:Http原生+AsyncTask

2.1. 当涉及较少的Bean数据提交时,例如用户注册:

private void initData() throws JSONException {
        OnLoadListener loadListener = dataList -> {
            for (int i = 0; i < questionConstantList.size(); i++) {
                urlList.add("http://119.23.223.94" + questionConstantList.get(i).videoPath);
                //这里是从服务端提交完返回的一个视频连接List
                //在我实际项目中提交一组Bean数据返回一个视频流
                //由于网络请求属于延时操作,这里我以一个监听器的形式回调Http请求结果
                //整个请求过程可以理解为 接口回调+安卓异步操作类AsyncTask 方案
            }
            videoAdapter.notifyDataSetChanged();
            //这里我将请求返回的数据用来刷新RecycleView
        };
  		/****************以JSONObject形式提交http请求****************/
  		/****************以下是我封装一组K/V数据的方式****************/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CP", "100");
        jsonObject.put("CI", new UserHelperTool(this).getHost().collegeID);
        jsonObject.put("NI", nodeConstant.NODE_UNIQUE_CODE);
        String URL = jsonObject.toString();
        //这里将封装完成的数据转化为string形式
        LoadInformationStreamTask loadInformationStreamTask = new LoadInformationStreamTask();
        //实例化自定义的AsyncTask 类
        loadInformationStreamTask.setLoadMyQuestionListener1(loadMyQuestionListener);
        //将回调监听器传入安卓自定义延时线程类 LoadInformationStreamTask
        loadInformationStreamTask.execute(URL);
        //启动 异步延时线程
    }

2.2 安卓http请求所使用异步线程 AsyncTask简述

泛型变量 Params 为内部执行方法 doInBackground 的参数类型
泛型变量 Progress 为执行进度类型
泛型变量 Result 为执行结果类型
实际上我通过set方式还自定义传入了 OnLoadListener 回调接口类

public static class LoadInformationStreamTask extends AsyncTask<String, Integer, List<QuestionConstant>> {
        private OnLoadListener loadListener1;

        void setLoadListener1(OnLoadListener loadListener1) {
            this.loadListener1 = loadListener1;
        }


        @Override
        protected void onPreExecute() {
        }

        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        protected List<QuestionConstant> doInBackground(String... params) {
            List<QuestionConstant> questionConstants = new ArrayList<>();
            HttpURLConnection connection;
            try {
                URL url = new URL(ServletValue.URLSQLQuestions);
                connection = (HttpURLConnection) url.openConnection();// 打开该URL连接
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");// 设置请求方法,“POST或GET”
                connection.setConnectTimeout(5000);// 设置连接建立的超时时间
                connection.setReadTimeout(50000);// 设置网络报文收发超时时间
                connection.setRequestProperty("Content-Type", "application/json");
                DataOutputStream os = new DataOutputStream(connection.getOutputStream());
                os.writeUTF(params[0]);
                os.flush();
                os.close();
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStreamReader in = new InputStreamReader(connection.getInputStream());
                    JSONArray jsonArrayData = new JSONArray(new BufferedReader(in).readLine());//如果没有data会赋值null,用get的话会报错
                    for (int i = 0; i < jsonArrayData.length(); i++) { //需要转成JSONObject再解析
                            QuestionConstant questionConstant = new QuestionConstant();
                            JSONObject objectToJson = jsonArrayData.getJSONObject(i);
                            questionConstant.id = objectToJson.getInt("ID");
                            questionConstant.collegeID = String.valueOf(objectToJson.getInt("CID"));
                            questionConstant.question = objectToJson.getString("QT");
                            questionConstant.createTime = objectToJson.getString("DT");
                            questionConstant.videoPath = objectToJson.getString("VP");
                            questionConstant.nodeID = objectToJson.getString("NID");
                            questionConstant.userID = objectToJson.getString("SID");
                            questionConstants.add(0, questionConstant);
                        }

                }
            } catch (
                    MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (
                    JSONException e) {
                e.printStackTrace();
            }
            return questionConstants; // 这里返回的结果就作为onPostExecute方法的入参
        }

        @Override
        protected void onPostExecute(List<QuestionConstant> questionConstantList) {
            loadMyQuestionListener1.init(questionConstantList);
            //onPostExecute 方法执行在UI线程中,这里我们使用回调接口刷新UI层数据
        }
    }

2.3方案二总结

实际上JSONObject还是以K/V形式提交数据,涉及到复杂的Bean类型时无论是K/V显得非常复杂,服务端使用诸如Spring-boot这样的架构时,几乎不会采用K/V形式交换数据,下面介绍以Gson形式直接完成 Bean ->JsonArray直接转换。

三、方案三:OkHttp框架 + Gson + runOnUiThread

请求的数据接口较多时使用该方案会节省开发时间,线程更加安全

3.1引入依赖

	implementation 'com.squareup.okhttp:okhttp:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp:3.12.8'
    implementation 'com.zhy:okhttputils:2.6.2'
    implementation 'com.alibaba:fastjson:1.2.40'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

3.2用以解析Lsit的JsonStringUtil工具类

public class JsonStringUtil {

    /**
     * 转成list
     */
    public static <T> ArrayList<T> stringToList(java.lang.String gsonString, Class<T> cls) {

        Gson gson = new Gson();
        ArrayList<T> list = new ArrayList<>();
        JsonArray array = new
                JsonParser().parse(gsonString).getAsJsonArray();
        if (array != null) {
            for (final JsonElement elem : array) {
                list.add(gson.fromJson(elem, cls));
            }
        }
        return list;
    }
}

3.3 将OkHttp框架必要方法封装为工具类OkHttpUtil

public class OkHttpUtil {
    private static final OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType
            .parse("image/png;charset=utf-8");
    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType
            .parse("text/x-markdown; charset=utf-8");
    static {
        client.setConnectTimeout(30, TimeUnit.SECONDS);
    }

    /**
     * 不会开启异步线程。
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return client.newCall(request).execute();
    }

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback) {
        client.newCall(request).enqueue(responseCallback);
    }

    /**
     * 根据url地址获取数据
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGetHttpRequest(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */


    public static String doPostHttpRequest(String url, String json,String apiSeq)
            throws IOException {
        Request request = new Request.Builder().url(url)
                .addHeader("api_seq",apiSeq)
                .post(RequestBody.create(JSON, json))
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String doPostHttpRequest2(String url, String json)
            throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder().url(url).post(body)
                .addHeader("content-type", "application/json").build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    public static String doPostImgHttpRequest(String url, File file)
            throws IOException {
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("buffer", file.getName(),
                        RequestBody.create(MEDIA_TYPE_PNG, file)).build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }
}

3.4 使用案例

runOnUiThread是Activity自带的方法,点击了解更多
用以刷新UI

3.4.1 在Activity中结合runOnUiThread方法

public void getAlarmMusicListByNet() {
        //获取服务端 音乐列表

        //Uri url = Uri.parse(MultipleDeviceConstants.getUrlRegisterUser(jsonString));
        new Thread(() -> {
            try {
                String responseString =
                        null;
                responseString = OkHttpUtil.doPostHttpRequest(MultipleDeviceConstants.getUrlAlarmVoiceList(),"{}","300");
                String finalResponseString = responseString;
                runOnUiThread(()->{
                    List<String> musicList =
                            JsonStringUtil.stringToList(finalResponseString,
                                    String.class);
                    for (String s:musicList){
                        alarmMusicAdapter.addItem(0,s);
                    }
                    //刷新音乐列表
                    alarmMusicAdapter.notifyDataSetChanged();
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

3.4.2 在Fragment中调用runOnUiThread

((MainActivity)getActivity()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //todo refresh ui 
            }
        });
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全面解读

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值