1. 程式人生 > >java呼叫引數為json字串型別的介面

java呼叫引數為json字串型別的介面

1、在yml檔案中配置自定義介面,如下:

flup:
  saveFlup: http://localhost:8080/flup/api/saveFlup

2、定義元件類繫結介面,方便呼叫(注意要將該類路徑放入@ComponentScan被spring自動掃描並且裝入bean容器)

package org.scbit.lsbi.mdc.questionnaire.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class QuestionnaireProperty {
   
    @Value("${flup.saveFlup}")
    private String saveFlup;
}

3、呼叫介面程式碼

    /**
     * 呼叫flup介面儲存相關隨訪資訊
     * @param basicInfoMap
     * @return
     */
    public Result saveFlup(Map<String, String> basicInfoMap) {
        //先講map轉為json字串型別
        String basicInfoJsonStr = JSON.toJSONString(basicInfoMap);
        String jsonStr = null;
        try {
            String url = questionnaireProperty.getSaveFlup();
            jsonStr = RequestUtil.executePost(url, basicInfoJsonStr);
        } catch (Exception e) {
            throw new ServiceException("介面呼叫失敗");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(jsonStr);
        Object jsonObj = jsonObject.get("code");
        if (200 == (int)(jsonObj)) {
            return Result.success();
        } else {
            return Result.fail("介面呼叫失敗");
        }
    }
以下為RequestUtil工具類的方法:
    public static String executePost(String url, String json) throws Exception {
        Assert.hasText(url);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        return getResult(url, httpClient, post);
    }

4、介面描述

   @RequestMapping("/saveFlup")
    @ResponseBody
    public Result saveFlup(@RequestBody String basicInfoJsonStr) {
        //TODO
        return Result.success();
    }

5、這樣就可以實現在一個專案中呼叫另外一個專案提供的介面啦,快去試試吧!不懂得可以下方留言哦! QQ:1564698367

6、筆者這裡不會呼叫引數為map型別的介面,只能先講map型別轉為json字串型別,再呼叫。