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

使用Rest-Assured请求返回500错误,Postman返回200如何解决?

问题解决:Rest-Assured POST请求返回500内部服务器错误

问题描述

在Postman中执行POST请求时可正常获得200响应:

  • 输入目标URL,选择POST方法
  • 添加Header:key为x-api-key并填入对应值
  • Body中传入listId及对应值

但使用Java+Rest-Assured+Maven编写请求时,收到500内部服务器错误:

Response status code: 500 & Response body: The page cannot be displayed because an internal server error has occurred.

问题代码

import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;

import static io.restassured.RestAssured.given;

public class TC001_CacheStatus {
    @Test
    public void CacheStatusCheck() throws IOException {
     
        // Set base URI of the API
        String baseUrl = "https://url.here";

        // Define headers
        String apiKey = "X-ApiKey";
        String apiValue = "value_here";

        // Define form data
        String formDataKey = "listId";
        String listId = "65cd9b8f";

        // Send POST request with headers and form data
        Response response =   RestAssured.given()
                                    .baseUri(baseUrl)
                                    .header("x-api-key", apiKey) 
                                    .multiPart("listId", listId)
                                    .contentType("multipart/form-data")
                                    .post("/endpoint")
                                    .andReturn();


        // Print response
        System.out.println("Response status code: " + response.getStatusCode());
        System.out.println("Response body: " + response.getBody().asString());

    }
}

解决方案

1. 修复API Key的Header传递错误

代码中header("x-api-key", apiKey)这一行存在参数传递错误:你将变量apiKey(值为字符串"X-ApiKey")作为Header的值传入,实际应该传入的是存储密钥的apiValue变量。

2. 匹配Postman的请求Body格式

Postman中提交表单参数通常使用x-www-form-urlencoded格式,而非代码中的multipart/form-data(后者多用于文件上传场景),调整代码如下:

Response response = RestAssured.given()
    .baseUri(baseUrl)
    .header("x-api-key", apiValue) // 修正为传入实际密钥值
    .formParam("listId", listId)
    .contentType(ContentType.URLENC)
    .post("/endpoint")
    .andReturn();

如果确认Postman确实使用multipart/form-data,仅需修正Header的API Key值即可。

3. 调试辅助:打印请求日志

开启Rest-Assured的日志功能,对比请求与Postman的差异:

Response response = RestAssured.given()
    .log().all() // 打印完整请求详情
    .baseUri(baseUrl)
    .header("x-api-key", apiValue)
    .formParam("listId", listId)
    .contentType(ContentType.URLENC)
    .post("/endpoint")
    .andReturn();
response.then().log().all(); // 打印完整响应详情

通过日志检查Header、Body、Content-Type是否与Postman完全一致,快速定位差异点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:52:53