与其他系统接口对接(java),json格式数据传递···OkHttpClient方式

上一种方式HttpURLConnection方式出现了点问题,就是在idea中启动服务一切正常。当时用tomcat部署项目时候,对方接口接收参数出现中文乱码问题。用了很多方式都没有解决,不知有没有大佬可以解决

引入依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.11.0</version>
        </dependency>

service

public Object getOpinionApplyResult(OpinionApplyResultInfoParamPojo oaripp) throws IOException, ParseException {
        String url = "http://services...com/"

        String paramValue = oaripp.getPlateColorCode() + oaripp.getTransCertificateCode() + oaripp.getVehicleNo();
        byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmac(paramValue);

        String param = JSON.toJSONString(oaripp);
        String hmacZ = Hex.encodeHexString(hmac);
        param = param.substring(0, param.length() - 1) + ",\"userCode\":\"" + user + "\",\"hmac\":\"" + hmacZ + "\"}";//转义处理
        System.out.println(param + "----param");
        //以上是对对方接口需要的数据进行处理 以下为具体的接口对接数据交换方式
        //与****系统交互,获取信息交换接口

        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, param))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response=okHttpClient.newCall(request).execute();

        int code = response.code();
        System.out.println(code+"-------------------code");
        String body = response.body().string();
//                  ****返回信息
        List<ApplyRuseltBakcMessagePojo> list = new ArrayList<>();
        if (code != 200) { // 非正常响应
            System.out.println("非正常响应");
            if ( body != null) {
                System.out.println(body + "-----------body");
                YZErrorParamPojo yze = JSON.parseObject(body, YZErrorParamPojo.class);
                if (yze != null) {
                    if ("100055".equals(yze.getErrorCode())) {
                        return ResultUtil.error(701, "你传入的数据不合法,请核实。");
                    } else if ("100042".equals(yze.getErrorCode())) {
                      ....业务逻辑
                    }
                }
            }
        } else {
            if (body != null) {
                System.out.println(body+"----body");
                list = JSON.parseObject(body, ArrayList.class);
                System.out.println(list.toString()+"----list.tostring()");

                return ResultUtil.success(list);
            }
        }
        return ResultUtil.error(-1,"未知错误");
    }

 ResultUtil  和  YZErrorParamPojo 都是封装的一些工具类以及封装的实体对象

具体的一些详细讲解 以及 工具类 pom依赖等各种详细信息 看上一篇博文与其他系统接口对接(java),json格式数据传递···HttpURLConnection方式

猜你喜欢

转载自blog.csdn.net/qq_32786139/article/details/82996519