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

Postman与Java调用接口返回400 Bad Request问题求助

问题分析与解决方案

核心原因

后端接口期望接收纯文本(plain text)格式的请求体,而非JSON对象。这是导致你遇到两种请求结果不同的根本原因:

  1. Postman传纯字符串"Ben"成功:
    此时Postman默认会将请求头Content-Type设为text/plain,后端能正确解析纯文本格式的请求体,所以请求成功。而当你传递{"name": "Ben"}这种JSON对象时,Postman自动把Content-Type设为application/json,后端无法解析不符合预期的格式,返回400错误。
  2. Java用JSONObject调用失败:
    你的代码生成的是JSON格式字符串({"name":"Ben"}),并且默认请求头Content-Type会被设置为application/json,和后端期望的纯文本格式不匹配,因此返回400错误。

解决方案

Java端修正代码

直接发送纯字符串"Ben",并指定请求头Content-Type为text/plain,以下是两种常见HTTP客户端的示例:

使用JDK原生HttpClient

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class PlainTextRequest {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("你的接口地址"))
                .header("Content-Type", "text/plain")
                .POST(HttpRequest.BodyPublishers.ofString("Ben"))
                .build();
        
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("响应状态码:" + response.statusCode());
        System.out.println("响应内容:" + response.body());
    }
}

使用Spring RestTemplate

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

public class SpringPlainTextRequest {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        HttpEntity<String> requestEntity = new HttpEntity<>("Ben", headers);

        ResponseEntity<String> response = restTemplate.postForEntity("你的接口地址", requestEntity, String.class);
        System.out.println("响应状态码:" + response.getStatusCode());
        System.out.println("响应内容:" + response.getBody());
    }
}

额外排查建议

  • 确认后端接口的接收逻辑:比如后端是否通过@RequestBody String name这种方式接收纯文本,而非接收包含name字段的实体类。
  • 若后端本应支持JSON格式请求,需检查后端是否正确配置了JSON解析依赖(如Jackson),以及接口是否正确使用@RequestBody注解接收实体对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:54:40