IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 远程调用接口修改某个单位jsonwe文件读取后转为bean对象 -> 正文阅读

[网络协议]远程调用接口修改某个单位jsonwe文件读取后转为bean对象

需求:由于最近公司需要调用别人写好得接口,需要各种数据转换,手动调用一个小时才几十条,有7000多条数据,所以自己写了一个自动化调用得代码进行调用

首先我们需要获取网站登录得cookie才能调用

  public static String getCookie() {
        String cookie = "";
        URL = "/chis/logon/myApps?urt=23397&uid=311999&pwd=123&deep=3";
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        StringBuffer params = new StringBuffer();
        // post请求参数
        //这里编码
        /*try {*/
        // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
        // params.append("name=" + URLEncoder.encode("&", "utf-8"));
        //params.append("&");
        JSONObject json = JSONObject.parseObject("{'url': 'logon/myApps?urt=23397&uid=311999&pwd=123&deep=3', 'httpMethod': 'POST'}");
        /* } *//*catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }*/
        // 创建post请求
        HttpPost httpGet = new HttpPost(DOMAIN + URL);

        System.out.println("请求路径" + httpGet);
        StringEntity entity = new StringEntity(json.toString(), "UTF-8");
        //创建Header
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setEntity(entity);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            try {
                response = httpClient.execute(httpGet);
                String setCookie = response.toString();
                int startCookieIndex = setCookie.indexOf(("Set-Cookie: ")) + 12;
                int endCookieIndex = setCookie.indexOf(("; Path"));
                cookie = setCookie.substring(startCookieIndex, endCookieIndex);
                //   System.out.println("response=============>" +cookie);

            } catch (IOException e) {
                e.printStackTrace();
            }

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();


            System.out.println("get请求响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                //   System.out.println("get请求响应内容长度为:" + responseEntity.getContentLength());
                byte[] bytes = EntityUtils.toByteArray(responseEntity);
                System.out.println("====未做处理===" + bytes.toString());
               /*
               因为EntityUtils中的toString源码。调用则关闭流。不能满足我接下来调用post请求,
               所以将它转为字节流。再转为字符串
                */
               /*
               调用字节输入流
                */
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
                BufferedReader br = new BufferedReader(inputStreamReader);
                String s = null;
                StringBuilder builder = new StringBuilder();
                while ((s = br.readLine()) != null) {
                    builder.append(s);
                }
                String result = builder.toString();
                //   System.out.println("get请求响应内容为:" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                // System.out.println(jsonObject);

            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cookie;
    }

然后我们需要将json数据转为对象

 /**
     * json转换为对象
     * @param jsonName
     * @param jsonPath
     * @param type
     * @param <T>
     * @return
     */
    public static <T> List<T> getOrderObjectsByClass(String jsonName , String jsonPath, Class<T> type){
        LinkedList<T> returnList = new LinkedList<T>();
        File file = new File(jsonPath);
        InputStreamReader isr = null;
        BufferedReader bufferedReader = null;
        try {
            isr = new InputStreamReader(new FileInputStream(file), "utf-8");
            bufferedReader = new BufferedReader(isr);

            JSONReader reader = new JSONReader(bufferedReader);
            reader.startArray();
            int a=0;
            while (reader.hasNext()) {a++;

                T readObject = reader.readObject(type);
                returnList.add(readObject);
            }
            System.out.println("进来"+a);
            reader.endArray();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            try {
                if(null != isr){
                    isr.close();
                }
                if(null != bufferedReader){
                    bufferedReader.close();
                }
            } catch (Exception e2) {
            }
        }
        return returnList;
    }

转换完之后调用接口 跟 别人得网站数据转为一致


    public static boolean callBasicHealthLoginGetCookieAndSavaOrUpdateDrugs(Drugs drugs) {
        int a=0;
        //通过药品序号查询药品表中有没有该条药品信息
        String savaOrUpdate = "";
        //如果有则修改,没有则添加
        if (drugs != null) {
            // 得到类对象
            Class clazz = drugs.getClass();
            // 得到所有属性
            Field[] fields = clazz.getDeclaredFields();
            //循环将所有为null的设置为空字符串
            for (Field field : fields) {
                //设置权限(很重要,否则获取不到private的属性
                field.setAccessible(true);
                try {
                    if (field.get(drugs) == null) {
                        System.out.println("field.get(drugs1)" + field.get(drugs));
                        field.set(drugs, "");
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            savaOrUpdate = "update";
        } else {
            savaOrUpdate = "create";
        }
        Map map = new HashMap();
        Map map2=new HashMap();
        map.put("serviceId", "chis.drugManageService");
        map.put("schema", "chis.application.pub.schemas.SQ_MBYP");
        map.put("op", savaOrUpdate);
        map.put("method", "execute");
        map.put("serviceAction", "saveCDMaintainDrug");
        //由于基卫那边的语法,所以全部写死
        //map.put("body", BeanUtil.copy(drugs1, TheBaseOfWhoDrug.class));
        map2.put("YPXH",Integer.parseInt(drugs.getYpxh()));
        map2.put("DL",drugs.getDl());
        map2.put("LBXH",drugs.getLbxh());
        map2.put("YPMC",drugs.getYpmc());
        map2.put("PYM",drugs.getPym());
        map2.put("QTMC1",drugs.getQtmc1());
        map2.put("PYM1",drugs.getPym1());
        map2.put("PYM2",drugs.getPym2());
        map2.put("QTMC2",drugs.getQtmc2());
        map2.put("QTMC3",drugs.getQtmc3());
        map2.put("PYM3",drugs.getPym3());
        map2.put("QTMC4",drugs.getQtmc4());
        map2.put("PYM4",drugs.getPym4());
        map2.put("QTMC5",drugs.getQtmc5());
        map2.put("PYM5",drugs.getPym5());
        map2.put("LBMC",drugs.getLbmc());
        map2.put("ZJFLAG",drugs.getZjflag());
        map2.put("SJXH",drugs.getSjxh());
        map2.put("YPGG",drugs.getYpgg());
        map2.put("YPDW",drugs.getYpdw());
        map2.put("YPJL",drugs.getYpjl());
        map2.put("JLDW",drugs.getJldw());
        map2.put("YCJL",drugs.getYcjl());
        map.put("body",map2);
        JSONObject json = new JSONObject(map);
        System.out.println("json================================》" + json);
      //调用修改得接口
        savaOrUpdateDrugs(getCookie(), json);
        return true;
    }

最后调用接口修改

    public static boolean savaOrUpdateDrugs(String cookie, JSONObject jsonParam) {
        a++;
        //设置URL
        URL = "/chis/*.jsonRequest";
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        StringBuffer params = new StringBuffer();
        // post请求参数
        //这里编码
        /*try {*/
        // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
        // params.append("name=" + URLEncoder.encode("&", "utf-8"));
        //params.append("&");

        /* } *//*catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }*/
        // 创建post请求
        HttpPost httpGet = new HttpPost(DOMAIN + URL);
        System.out.println("请求路径" + httpGet);
        StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
        //创建Header
        httpGet.setHeader("Content-Type", "application/json");

        httpGet.setHeader("Cookie", cookie);
        httpGet.setEntity(entity);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            try {
                response = httpClient.execute(httpGet);
//                String setCookie = response.toString();
//                int startCookieIndex = setCookie.indexOf(("Set-Cookie: ")) + 12;
//                int endCookieIndex = setCookie.indexOf(("; Path"));
                cookie=setCookie.substring(startCookieIndex, endCookieIndex);
                System.out.println(response);

            } catch (IOException e) {
                e.printStackTrace();
            }

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();


            System.out.println("get请求响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("get请求响应内容长度为:" + responseEntity.getContentLength());
                byte[] bytes = EntityUtils.toByteArray(responseEntity);
                System.out.println("====未做处理===" + bytes.toString());
               /*
               因为EntityUtils中的toString源码。调用则关闭流。不能满足我接下来调用post请求,
               所以将它转为字节流。再转为字符串
                */
               /*
               调用字节输入流
                */
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
                BufferedReader br = new BufferedReader(inputStreamReader);
                String s = null;
                StringBuilder builder = new StringBuilder();
                while ((s = br.readLine()) != null) {
                    builder.append(s);
                }
                String result = builder.toString();
                System.out.println("get请求响应内容为:" + result);
                System.out.println("================================================>第"+a);
                //JSONObject jsonObject = JSONObject.parseObject(result);
                //    System.out.println(jsonObject);

            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-09-10 11:12:15  更:2021-09-10 11:13:40 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年6日历 -2024/6/18 19:25:31-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码