**Java 发送http请求的两种方式**

前置条件
     @Resource
      private RestTemplate restTemplate;

方式一:

/**
     * 领劵测试方法
     * @throws IOException
     */
    @Test
    public void aa() throws IOException {
        try {
            //接口路径
            String createOrderUrl = "https://**********************************";
            //参数
            ManualCouponsReq req = new ManualCouponsReq();
            req.setAppId("参数1");
            req.setOpenId("参数3");
            req.setCouponId("参数3");
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            RestTemplate restTemplate1 = new RestTemplate();
            log.info("手动领劵传入参数:{},地址:{}", JSON.toJSONString(req, SerializerFeature.MapSortField), createOrderUrl);
            ResponseEntity<ManualCouponsResp> resp = restTemplate1.postForEntity(createOrderUrl, req, ManualCouponsResp.class);
            log.info("手动领劵传返回结果:{}", JSON.toJSONString(resp, SerializerFeature.MapSortField));
        } catch (Exception e) {
            log.error("手动领劵传失败", e);
        }
    }

方式二:

/**
 * 领劵测试方法
 * @throws IOException
 */
@Test
public void bb() throws IOException {
    try {
        //接口路径
        String createOrderUrl = "https://******";
        //参数
        ManualCouponsReq manualCouponsReq=new ManualCouponsReq();
        manualCouponsReq.setAppId("参数1");
        manualCouponsReq.setOpenId("参数3");
        manualCouponsReq.setCouponId("参数3");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //设置类型
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<ManualCouponsReq> formEntity = new HttpEntity<>(manualCouponsReq, headers);
        //发送数据方法
        ResponseEntity<ManualCouponsResp> forEntity = restTemplate.postForEntity(createOrderUrl, formEntity, ManualCouponsResp.class);
        //得到返回的数据body
        ManualCouponsResp body = forEntity.getBody();
        System.out.println(body.toString());
    }catch (Exception e){
        e.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值