【RestTemplate发送post、get请求】

RestTemplate发送post、get请求

使用RestTemplate发送post请求

public String restTemplateByPost(String apiUrl, Map<String,String> reqParam, MediaType accept){
        String body = null;
        try{
            //获取数据接口
            log.debug("请求的参数为{}",reqParam.toString());
            log.debug("请求地址为{}",apiUrl);

            //创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //通过设置 Accept,服务端就可以在响应头中设置正确的 Content-Type 类型,以确保客户端在接收响应时将其正确解析
            if(accept != null){
                headers.setAccept(Arrays.asList(accept));
            }
            //创建请求对象
            Map<String, Object> postParameters = new HashMap<>();
            reqParam.forEach((k,v) -> {
                postParameters.put(k, v);
            });
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(postParameters, headers);
            ResponseEntity<String> res = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, String.class);
            body = res.getBody();
            log.debug("调用三方远程请求的返回为:{}",body);
//            int statusCode = res.getStatusCodeValue();
//            if(statusCode != 201 && statusCode != 200){
//                log.info("调用三方接口返回异常{}:",body);
//                throw new RuntimeException("调用三方接口返回异常:"+body);
//            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new RunTimeCoreException("001","调用三方接口异常:"+e.getMessage());
        }
        if(StringUtils.isBlank(body)){
            throw new RunTimeCoreException("002","调用三方接口返回异常:"+body);
        }
        return body;
    }

使用RestTemplate发送get请求

public String restTemplateByGet(String apiUrl, Map<String,String> reqParam){
        log.debug("请求的参数为{}",reqParam.toString());
        log.debug("请求地址为{}",apiUrl);
//        JSONObject jsonObject = null;
        String body = null;
        try{
            //创建请求头
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<MultiValueMap<String,String>> request = new HttpEntity(null,headers);

            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl);
            ResponseEntity<String> res;
            //如果存在參數
            if(!reqParam.isEmpty()){
                for (Map.Entry<String,String> e: reqParam.entrySet()) {
                    //构建查询参数
                    builder.queryParam(e.getKey(),e.getValue());
                }
                //拼接好参数后的URl//test.com/url?param1={param1}&param2={param2};
                String reallyUrl=builder.build().toString();
                log.info("发送get请求拼接好参数的Url:{}",reallyUrl);
                res  =restTemplate.exchange(reallyUrl, HttpMethod.GET,request,String.class);
            }else{
                res=restTemplate.exchange(apiUrl,HttpMethod.GET,request,String.class);
            }
            body = res.getBody();
            log.debug("调用三方远程请求的返回为:{}",body);
//            jsonObject = JSON.parseObject(body);

        }catch (Exception e){
            log.error(e.getMessage());
            throw new RunTimeCoreException("001","调用三方接口异常:"+e.getMessage());
        }

        if(StringUtils.isBlank(body)){
            throw new RunTimeCoreException("002","调用三方接口返回异常:"+body);
        }
//        return body;
        return body;

    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!关于使用RestTemplate进行远程调用,我可以给你一些帮助。RestTemplate是Spring框架提供的一个用于发送HTTP请求的客户端工具。你可以使用它来调用其他系统的RESTful API。 首先,你需要在你的项目中导入RestTemplate的依赖。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 接下来,你可以在你的代码中使用RestTemplate发送HTTP请求。下面是一个简单的示例: ```java import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RemoteServiceClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/endpoint"; ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); String responseBody = response.getBody(); System.out.println(responseBody); } } ``` 在上面的示例中,我们创建了一个RestTemplate实例,并使用exchange()方法发送了一个GET请求。你可以根据需要选择合适的HTTP方法(如GET、POST、PUT等)和请求体内容。 当然,在实际应用中,你可能还需要处理错误、设置请求头、传递URL参数等。RestTemplate提供了一些其他的方法和功能来满足这些需求。如果你需要更多细节或更复杂的使用场景,可以查阅Spring官方文档或其他相关资源。 希望这些信息对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值