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 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字符串类型,再调用。

你可能感兴趣的:(Java学习笔记)