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

为何我的k6 HTTP POST请求失败?Curl正常但k6返回405错误

问题:k6脚本调用OAuth2令牌接口返回405错误,但curl请求正常

我有一个curl命令可以正常获取200响应及access_token:

curl --location 'https://amazonURL/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic XXX' \
--data-urlencode 'grant_type=client_credentials'

但等效的k6脚本执行后返回405错误,脚本如下:

import http from 'k6/http';
import { sleep, check } from 'k6';
import encoding from 'k6/encoding';

  const url_auth = 'https://amazonURL/oauth2/token';
  const auth_payload = JSON.stringify({'grant_type': 'client_credentials'});
  const auth_params = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic XXX'
      }
  };

  let auth_response = http.post(url_auth, auth_payload, auth_params);

请问我哪里操作有误?


问题原因与修复方案

你的k6脚本存在两个关键错误,导致接口返回405:

  1. Content-Type不匹配
    curl请求明确使用application/x-www-form-urlencoded,但k6脚本里错误设置为application/json,而OAuth2的client_credentials模式默认要求用表单编码格式提交参数。

  2. 请求体格式错误
    你用JSON.stringify()生成了JSON格式的请求体,但curl用--data-urlencode提交的是表单键值对格式,服务器无法解析JSON格式的参数,因此拒绝处理请求,返回405错误。

修复后的k6脚本(两种可选方式)

方式1:使用k6内置的form参数(推荐)

k6会自动处理表单编码并设置正确的Content-Type:

import http from 'k6/http';
import { sleep, check } from 'k6';

const url_auth = 'https://amazonURL/oauth2/token';
const auth_params = {
    headers: {
        'Authorization': 'Basic XXX'
    },
    form: {
        'grant_type': 'client_credentials'
    }
};

let auth_response = http.post(url_auth, null, auth_params);

// 可选:添加检查逻辑
check(auth_response, {
    '获取令牌成功': (res) => res.status === 200,
    '返回access_token': (res) => res.json().access_token !== undefined
});

sleep(1);

方式2:手动构造表单编码的请求体

手动设置Content-Type并构造正确的请求体格式:

import http from 'k6/http';
import { sleep, check } from 'k6';

const url_auth = 'https://amazonURL/oauth2/token';
const auth_payload = 'grant_type=client_credentials';
const auth_params = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic XXX'
    }
};

let auth_response = http.post(url_auth, auth_payload, auth_params);

// 可选:添加检查逻辑
check(auth_response, {
    '获取令牌成功': (res) => res.status === 200,
    '返回access_token': (res) => res.json().access_token !== undefined
});

sleep(1);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:05:18