Spring Boot调用api delete接口

 Spring Boot调用api delete接口

示例:

   /**
     * 调用api delete接口
     *
     * @param url
     * @author li.zhm
     * @date 2022/8/20 14:07
     * @history <author>  <time>  <version>  <desc>
     */
    public static void sendDelete(String url) {
        log.info("请求delete地址:{}", url);
        String body = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 创建delete方式请求对象
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig =
                RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpDelete.setConfig(requestConfig);
        // 设置header信息, 指定报文头【Content-type】 【User-Agent】
        httpDelete.setHeader("Content-type", "application/json");
        httpDelete.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        try {
            // 执行请求操作,并拿到结果(同步阻塞)
            response = client.execute(httpDelete);
            log.info("response 返回状态码:{}", response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                log.info("AMF取消订阅成功!");
            } else {
                log.error("response 返回状态码异常:{}", response.getStatusLine().getStatusCode());
            }
            // 释放链接
            response.close();
        } catch (IOException e) {
            log.error("调用amf-delete sub api异常,{0}", e);
            e.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("关闭http client异常,{0}", e);
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭http response异常,{0}", e);
                    e.printStackTrace();
                }
            }
        }
    }

 

posted @ 2022-08-20 16:08  整合侠  阅读(261)  评论(0编辑  收藏  举报