欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate 发送get、put、post 请求

程序员文章站 2022-06-25 20:27:08
...

RestTemplate 发送get、put、post 请求

/**
     * 发送请求Get请求
     *
     * @param url   请求接口
     * @param param 请求参数
     */
    private JSONObject sendGet(String url, JSONObject param) {
        JSONObject jsonObject = null;
        try {
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity = new HttpEntity<>(param, headers);
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            jsonObject = JSON.parseObject(resEntity.getBody());
        } catch (Exception e) {
            if (e.toString().contains("timed out")) {
                throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
            }
            throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
        }
        return jsonObject;
    }
    
    /**
     * 发送请求Put请求
     *
     * @param url   请求接口
     * @param param 请求参数
     */
    private JSONObject sendPut(String url, JSONObject param) {
        JSONObject jsonObject = null;
        try {
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity = new HttpEntity<>(param, headers);
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
            jsonObject = JSON.parseObject(resEntity.getBody());
        } catch (Exception e) {
            if (e.toString().contains("timed out")) {
                throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
            }
            throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
        }
        return jsonObject;
    }

 /**
     * 发送请求Post请求
     *
     * @param url   请求接口
     * @param param 请求参数
     */
    private JSONObject sendPost(String url, JSONObject param) {
        JSONObject jsonObject = null;
        try {
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity = new HttpEntity<>(param, headers);
            jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);
        } catch (Exception e) {
            if (e.toString().contains("timed out")) {
                throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
            }
            throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
        }
        return jsonObject;
    }
相关标签: Java