與其他系統介面對接(java),json格式資料傳遞···OkHttpClient方式
阿新 • • 發佈:2018-11-13
上一種方式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方式