今天遇到一個問題,重構老系統時,前端傳遞的參數是一個json,controller層能夠用@ResponseBody來接收。
由於新系統用的是spring cloud這一套,調用其餘服務使用的是feign的形式,找了一圈沒有找到合適的方案,因而用OkHttpClient來處理了,這裏作個記錄。(仍相信feign也能處理,可是剛上手spring cloud,不少都還不是很熟,這裏備註做爲本身todo的事項)html
先看看參數格式:前端
再看看controller層:spring
這裏使用@RequestBody就能夠直接接收到了,後面就直接鋪上OKHttpClient的解決代碼:json
public String createBatch(String jsonString, String url) { MediaType json = MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create(json, jsonString); Request requestPost = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; String result = null; try { response = client.newCall(requestPost).execute(); if (response.body() != null) { result = response.body().string(); } } catch (IOException e) { throw new WebCatException(500, e.getMessage()); } if (StringUtils.isNotBlank(result)) { JSONObject jsonObject = JSONObject.parseObject(result); result = jsonObject.getString("data"); } return result; }
參考:https://blog.csdn.net/zhan10001/article/details/78461143微信
分類: 工做經驗app
一枝花算不算浪漫
post