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

Spring RestTemplate向Salesforce Post产品报400错误,Postman却成功

问题根源:请求体格式不匹配

你遇到的问题核心原因很直接:Postman发送的是JSON格式的请求体,但你的RestTemplate代码用了LinkedMultiValueMap,这会默认发送application/x-www-form-urlencoded(表单)格式的数据,而Salesforce的sobjects/Product2接口仅接受JSON格式的请求,因此接口会拒绝你的请求。


解决方案:切换为JSON格式请求体

你需要把请求体从表单格式改成JSON格式,有两种常用实现方式:

方式1:用POJO类封装请求体(推荐,更规范)

先定义一个和请求字段对应的实体类:

public class ProductRequest {
    private String Name;
    private String product_Reference__c;

    // 构造方法
    public ProductRequest(String name, String productReference) {
        this.Name = name;
        this.product_Reference__c = productReference;
    }

    // 省略getter和setter,也可以用Lombok的@Data注解简化
}

然后修改你的createProduct方法:

public AddProductResponse createProduct(@NonNull AuthenticationTokenResponse authenticationTokenResponse) {
    String url = authenticationTokenResponse.getInstance_url() + "/services/data/v39.0/sobjects/Product2";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", "Bearer " + authenticationTokenResponse.getAccess_token());

    // 使用POJO作为JSON请求体
    ProductRequest requestBody = new ProductRequest("Product Name", "SOMERef");
    HttpEntity<ProductRequest> requestEntity = new HttpEntity<>(requestBody, headers);

    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<AddProductResponse> response = restTemplate.exchange(
                url, 
                HttpMethod.POST, 
                requestEntity, 
                AddProductResponse.class
        );
        return response.getBody();
    } catch (Exception e) {
        LOG.debug("Error creating product: {}", e.getMessage());
        e.printStackTrace();
    }
    return null;
}

方式2:用HashMap快速构造请求体(适合临时测试)

如果不想创建POJO,也可以直接用HashMap来生成JSON:

// 替换请求体部分代码
Map<String, String> requestBody = new HashMap<>();
requestBody.put("Name", "Product Name");
requestBody.put("product_Reference__c", "SOMERef");
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

额外排查小贴士
  • 确保RestTemplate已配置JSON消息转换器:Spring Boot默认会自动配置MappingJackson2HttpMessageConverter,如果是手动创建RestTemplate,记得手动添加该转换器。
  • 优化异常日志:捕获异常时可以打印响应的状态码和错误内容,方便快速定位问题,比如:
    if (e instanceof HttpClientErrorException) {
        HttpClientErrorException ex = (HttpClientErrorException) e;
        LOG.debug("Response status: {}, Error content: {}", ex.getStatusCode(), ex.getResponseBodyAsString());
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:32:32