使用restTemplate.postForEntity()

这个博客展示了如何在Java中使用`@Component`和`@Autowired`注解注入`RestTemplate`来发送HTTP POST请求。代码通过`MockPropertiesUtil`从配置文件中获取URL,并设置请求头为JSON类型。接收到响应后,日志记录请求和响应报文,最后返回响应内容。
@Component
public class RemoteQuestUtil {

    @Autowired
    private RestTemplate restTemplate;

    public String send(String srvcCode, String request){
        //srvcCode 获取对应交易 现场适配
        MockPropertiesUtil instance = MockPropertiesUtil.getInstance();
        String url = instance.getProperty(srvcCode);
		
		//处理接收接口只支持JSONOBject
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request1 = new HttpEntity<>(request, headers);
        log.info("请求报文:{}",request);

        ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request1, String.class);
        String resp = jsonObjectResponseEntity.getBody();
        log.info("响应报文:{}",resp);

        return resp;

    }
}

MockPropertiesUtil

public class MockPropertiesUtil {
    public  static Properties pro = new Properties();
    public static MockPropertiesUtil instance = new MockPropertiesUtil();
    public static MockPropertiesUtil getInstance() {
        return instance;
    }
    static {

        InputStream in ;
        try {
                in = MockPropertiesUtil.class.getClassLoader().getResourceAsStream("mock-properties.properties"); //加载文件将文件加载为
        pro = new Properties();
            pro.load(in);
        } catch (IOException e) {
            log.error("加载Mock配置文件[mock-properties.properties]时异常",e);
            throw new PlatformException(PlatformError.LOADCONFIG_ERROR);
        }
        try {
            if (in != null){
                in.close();
            }
        } catch (IOException e) {
            log.error("关闭流异常",e);
        }
    }


    public String getProperty(String key) {
        if (StringUtil.isEmpty(key)) {
            log.warn("key is null.");
            return null;
        }
        if (!pro.containsKey(key)){
            log.info("无此服务码:{}",key);
            throw new PlatformException(PlatformError.GET_URL_BY_CODE_ERROR);
        }
        //通过键值获得对应的url key=url
        String url = pro.getProperty(key);
        log.info("服务码:{},对应的url为:{}",key,url);
        return url;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值