美文网首页
JSON报文创建与接收 JSONObject or JSONAr

JSON报文创建与接收 JSONObject or JSONAr

作者: DCMeng | 来源:发表于2019-10-28 10:04 被阅读0次
// 构建报文
JSONObject rootJson = new JSONObject();
// 赋值
rootJson.put("unique_code", qniqueCode);
JSONObject dataJson = null;
JSONArray dataList = new JSONArray();
for (TransferFundResult rfr : rfrResultList) {
    for (Map.Entry<SubjectEnum, TransferFundItem> entry : rfr.entrySet()) {
        entry.getValue();
        // receive_number ★收款会员号
        dataJson = new JSONObject();
        dataJson.put("receive_number", rfr.getTransferMainbodyOrgMemberId());
        // pay_type ★付款类别
        dataJson.put("pay_type", rftValId.get(entry.getKey().getValue()) + "");
        // amount 金额
        dataJson.put("amount", entry.getValue().getAmount().toString() + "");
        // group_state ★支付状态
        dataJson.put("group_state", entry.getValue().getAllocationResult().getValue() + "");
        // group_error_info ★错误信息
        dataJson.put("group_error_info", entry.getValue().getResult());
                dataList.add(dataJson);
    }
}
rootJson.put("data_list", dataList);
/***************************************************
     * @Description 使用http协议发送字节流消息
     * @Date 2019-10-22 10:13
     * @param hostIp    远程主机IP地址
     * @param port      远程主机端口
     * @param path      远程主机服务路径
     * @param method    提交方式
     * @param sendBytes 发送的字节
     * @return
     * @throws IOException byte[]
 ***************************************************/
public static byte[] sendHttpBytesMessage(String hostIp, int port, String path, String method, byte[] sendBytes)
            throws IOException {
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        String urlStr = "http://" + hostIp + ":" + port + "/" + path;
        URL url = new URL(urlStr);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "text/xml");
        httpURLConnection.setRequestMethod(method.toUpperCase());
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);

        bos = new BufferedOutputStream(httpURLConnection.getOutputStream());
        bos.write(sendBytes);
        bos.flush();
        bos.close();
        bis = new BufferedInputStream(httpURLConnection.getInputStream());
        int responseCode = httpURLConnection.getResponseCode();
        byte[] temp = new byte[4096];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        if (responseCode == httpURLConnection.HTTP_OK) {
            while ((len = bis.read(temp)) > 0) {
                baos.write(temp, 0, len);
            }
        } else {
            System.out.println("请求响应返回码=" + responseCode);
        }

        return baos.toByteArray();
}
// 接收响应
        byte[] response = null;
        try {
            response = ConmunicationUtil.sendHttpBytesMessage("192.168.1.1", 8080, "lpapiLYPH0006.action",
                    "post", reqMsg.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("response =>> " + new String(response, "utf-8"));

// 对端接收解析
// 以流的方式获取请求报文内容
        String reqMsg = null;
        System.out.println("contentLength =" + this.request.getContentLength());
        byte[] tempContentBytes = new byte[4096];
        int len = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean flag = true;
        try {
            BufferedInputStream bis = new BufferedInputStream(this.request.getInputStream());
            while ((len = bis.read(tempContentBytes)) >= 0) {

                System.out.println("tempContentBytes=" + Arrays.toString(tempContentBytes));
                baos.write(tempContentBytes, 0, len);
            }
            reqMsg = baos.toString("utf-8");
            log.debug("接受的请求字节码=" + Arrays.toString(baos.toByteArray()));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            flag = false;
            responseMsg = settlementResult.getFailedMesageTemplate(999, "字符编码处理异常-" + e1.getMessage());
            log.error("请求报文处理异常", e1);
        } catch (IOException e1) {
            e1.printStackTrace();
            flag = false;
            responseMsg = settlementResult.getFailedMesageTemplate(999, "I/O处理异常-" + e1.getMessage());
            log.error("请求报文处理异常", e1);
        } finally {
            if (!flag) {
                this.sendResponseMessage(responseMsg, "UTF-8");
            }
        }
JSONObject json = null;
// 流转换JSON
json = JSONObject.fromObject(reqMsg);
// JsonPath取值
String logisticMemberCode = JsonPath.read(json, "$.transit_code");
JSONArray dayList = JsonPath.read(json, "$.data_list");
for (int i = 0; i < dayList.size(); i++) {
  JSONObject job = dayList.getJSONObject(i);
  payType = Integer.parseInt((String) JsonPath.read(job, "$.pay_type"));
}

相关文章

网友评论

      本文标题:JSON报文创建与接收 JSONObject or JSONAr

      本文链接:https://www.haomeiwen.com/subject/easvvctx.html