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

SpringBoot中如何向外部服务发送携带数据的POST请求?

SpringBoot 向外部服务发送POST请求落地实现

全程用SpringBoot原生组件实现,不需要引入第三方HTTP工具包,代码复制后修改少量配置即可运行。

第一步:确认基础依赖

只要项目引入了SpringWeb模块依赖即可,不需要额外加包,检查pom.xml中存在以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

第二步:注册RestTemplate到Spring容器

SpringBoot默认没有自动装配RestTemplate,直接注入会报找不到Bean的错误,先新增一个配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

第三步:编写请求发送逻辑

先明确目标地址完整格式为http://10.20.30.111:30/实际接口路径,记得替换成对方提供的具体端点路径,不要遗漏http://前缀。以下覆盖两种最常见的传参场景,根据对方接口要求选对应的实现即可。

场景1:对方接口接收JSON格式参数(90%以上业务接口用这个格式)

新增Service类封装请求逻辑:

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ExternalRequestService {
    @Resource
    private RestTemplate restTemplate;
    // 替换成你的完整目标接口地址
    private static final String TARGET_URL = "http://10.20.30.111:30/替换为对方提供的接口路径";

    public String sendPostTest(String field1Value, Integer field2Value) {
        // 组装请求参数,key必须和对方要求的字段名完全一致
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("field1", field1Value);
        requestParams.put("field2", field2Value);

        // 设置请求头,声明传输JSON格式数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 组装请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);

        try {
            // 发送POST请求,如果对方返回固定结构JSON,可自定义Java类替换String.class,直接接收结构化对象
            ResponseEntity<String> response = restTemplate.exchange(
                    TARGET_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            if (response.getStatusCode().is2xxSuccessful()) {
                // 返回对方的测试校验结果
                return response.getBody();
            }
            return "请求失败,响应状态码:" + response.getStatusCode().value();
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }
}

场景2:对方接口接收Form表单格式参数

只需要修改参数容器和请求头格式即可,其余逻辑和JSON场景完全一致:

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

// 组装表单格式参数
MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<>();
formParams.add("field1", field1Value);
formParams.add("field2", field2Value);

// 请求头改为表单格式
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

// 组装请求实体时传入formParams即可
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formParams, headers);

第四步:写测试接口验证效果

新增Controller类,启动项目后可以直接访问测试:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class TestController {
    @Resource
    private ExternalRequestService externalRequestService;

    @GetMapping("/testPost")
    public String testSend(@RequestParam String data1, @RequestParam Integer data2) {
        return externalRequestService.sendPostTest(data1, data2);
    }
}

启动项目后,浏览器访问http://localhost:本地项目端口/testPost?data1=测试值&data2=123,就能拿到目标服务返回的测试结果。

新手常见踩坑点

  • 地址前缀不能漏:目标地址必须加http://前缀,直接写IP端口会报未知协议错误
  • 参数名必须匹配:传参的key要和对方接口要求的字段名完全一致,大小写敏感,否则对方服务会校验失败
  • 先测网络连通性:写代码前先在本地命令行执行telnet 10.20.30.111 30,如果连不上先排查网络、防火墙问题,这种情况代码写对了也无法正常请求
  • 自定义请求头直接加:如果对方接口要求传token、签名等鉴权信息,直接调用headers.add("头字段名", "对应值")添加即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 01:21:34