1. 程式人生 > >Spring Boot 呼叫另外專案的介面方法,傳遞json引數

Spring Boot 呼叫另外專案的介面方法,傳遞json引數

1 描述:呼叫別的專案介面方法,傳遞json資料引數,然後返回json資料

2程式碼如下

@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
   //此處將要傳送的資料轉換為json格式字串
   String jsonText = "{id:1}";
   JSONObject json = (JSONObject) JSONObject.parse(jsonText);
   JSONObject sr = this.doPost(json);
   System.out.println("返回引數:" + sr);
   return sr.toString();
}

public static JSONObject doPost(JSONObject date) {
   HttpClient client = HttpClients.createDefault();
   // 要呼叫的介面方法
   String url = "http://192.168.1.101:8080/getJson";
   HttpPost post = new HttpPost(url);
   JSONObject jsonObject = null;
   try {
      StringEntity s = new StringEntity(date.toString());
      s.setContentEncoding("UTF-8");
      s.setContentType("application/json");
      post.setEntity(s);
      post.addHeader("content-type", "text/xml");
      HttpResponse res = client.execute(post);
      String response1 = EntityUtils.toString(res.getEntity());
      System.out.println(response1);
      if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
         String result = EntityUtils.toString(res.getEntity());// 返回json格式:
         jsonObject = JSONObject.parseObject(result);
      }
   } catch (Exception e) {
      throw new RuntimeException(e);
   }
   return jsonObject;
}