You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java执行CURL带请求体的DELETE请求失败,求解决及替代方案

解决Spring Boot中执行带请求体的DELETE请求返回空的问题

一、修复curl命令执行的问题

代码返回空的核心原因包括:命令参数拆分错误、未等待进程执行完成、未读取错误输出流。以下是修复后的代码:

import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class CurlExecutor {
    public static void main(String[] args) throws Exception {
        // 手动构造参数列表,避免带空格的参数被错误拆分
        List<String> command = List.of(
                "curl",
                "-X", "DELETE",
                "你的目标URL",
                "-H", "Authorization: Token XXX",
                "-H", "Content-Type: application/json",
                "-d", "你的请求体ENTITY内容"
        );

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        // 合并标准输出和错误输出,统一读取避免遗漏信息
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        // 等待curl命令执行完毕
        int exitCode = process.waitFor();

        // 读取输出内容
        InputStream inputStream = process.getInputStream();
        String test = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        
        if (!test.isEmpty()) {
            String statusMessage = new JSONObject(test).getString("status_message");
            System.out.println(statusMessage);
        } else {
            System.err.println("命令执行异常,退出码:" + exitCode);
        }
    }
}

关键改进点:

  • 用List.of()手动构造参数,避免split(" ")错误拆分带空格的参数(如Authorization头)。
  • 调用process.waitFor()等待进程执行完成后再读取输出。
  • 开启redirectErrorStream(true),将错误输出合并到标准输出,避免因错误信息在stderr导致stdout为空。

二、推荐使用Spring自带HTTP客户端(替代curl)

在Spring Boot中调用外部curl命令并非最佳实践,推荐使用Spring原生的RestTemplate或WebClient,更稳定且易于维护:

方案1:使用RestTemplate

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class DeleteRequestWithRestTemplate {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "你的目标URL";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Token XXX");
        headers.set("Content-Type", "application/json");

        // 设置请求体
        String requestBody = "你的请求体ENTITY内容";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送DELETE请求
        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.DELETE,
                requestEntity,
                Map.class
        );

        // 解析响应
        String statusMessage = (String) response.getBody().get("status_message");
        System.out.println(statusMessage);
    }
}

方案2:使用WebClient(非阻塞,适配Spring WebFlux)

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

public class DeleteRequestWithWebClient {
    public static void main(String[] args) {
        WebClient webClient = WebClient.create("你的基础URL");

        String requestBody = "你的请求体ENTITY内容";

        Mono<Map> responseMono = webClient.delete()
                .uri("你的接口路径")
                .header("Authorization", "Token XXX")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class);

        // 阻塞获取结果(非阻塞场景可改用subscribe异步处理)
        Map responseBody = responseMono.block();
        String statusMessage = (String) responseBody.get("status_message");
        System.out.println(statusMessage);
    }
}

这两种方案无需依赖外部工具,直接在JVM内发送HTTP请求,安全性、效率和可维护性都更优。

内容的提问来源于stack exchange,提问作者Serdar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 05:10:04