RestTemplate 带泛型的POST请求方法,调用rest接口

项目需要,研究了一下RestTemplate 调用rest接口方法,由于项目中只用到POST请求,所以,贴一段POST请求的方法,其他请求,各位看官自行封装吧,一个道理。

    /**
     * 发送post请求
     * @param url   请求地址
     * @param map   请求参数对象
     * @return
     */
    public  T sendPostRequest(String url, Map map,Class tClass) {
        //将入参,出参,请求时间,请求地址存入mongodb中
        Map mongodbMap = new HashMap<>();
        HttpStatus statusCode =null;
        String tJsonStr = null;
        //传入的参数,我这里使用map,key叫obj
        String requestBody = JSONObject.toJSONString(map.get("obj"));
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity httpEntity = new HttpEntity(requestBody, headers);
        try {
            ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, tClass);
            //获取HttpStatus
            statusCode = responseEntity.getStatusCode();
            //获取内容
            T t = responseEntity.getBody();
            tJsonStr = JSON.toJSONString(t);
            //判断是否返回code为0
            if (statusCode.value() == HttpStatus.OK.value()){
                //处理返回的内容
            }
        }catch (Exception e){
                //出现异常的时候,处理
        } finally {
                //这里看具体需求,我们是把log日志存到mongodb中
        }
        return null;
    }

 

你可能感兴趣的:(RestTemplate 带泛型的POST请求方法,调用rest接口)