zoukankan      html  css  js  c++  java
  • 关于OkHttp同步请求的小错误

    今天进行OkHttp的同步请求

    写的都是按照官方的去写的

    但是返回的东西却不是我想要的

    原因是我直接拿到Response后,直接Response.toString,想要拿到返回值

    但是这样是错误的,正确的应该是Response.body().string这样拿到的才是正确的 服务器给的返回值

    下面附上 同步请求正确的代码

        /**
         * 通过get请求,获取json实例
         *
         * @param urlStr 请求地址
         */
        private String getString(String urlStr) {
            ResponseBody responseBody = null;
    
            try {
                Response response = execute(urlStr);
    
                if (response == null)
                    return null;
    
                responseBody = response.body();
                return responseBody.string();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (responseBody != null)
                    responseBody.close();
            }
            return null;
        }
    
        public Response execute(String url) {
            Request request = new Request.Builder().url(url).build();
            try {
                Response response = client.newCall(request).execute();
    
                if (response.isSuccessful())
                    return response;
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    

      

  • 相关阅读:
    ajax代码及简单封装
    web开发中不同设备浏览器的区分
    JS实现带复选框的下拉菜单
    常用浏览器的编码设置
    PHP实现实现数字补零格式化
    Linux杂碎2/SHELL
    OS
    Linux sudoers
    代理缓存服务器squid
    es6
  • 原文地址:https://www.cnblogs.com/fengfenghuifei/p/7574457.html
Copyright © 2011-2022 走看看