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

使用Python LocustIO压测时POST请求报Bad Request,如何修正JSON参数格式?

Fixing Bad Request Errors in LocustIO POST Requests (JSON Formatting Issues)

Hey there, let's get that Bad Request error sorted out. The root cause here is almost certainly how you're constructing your JSON payload—manually building strings with escaped quotes is error-prone and often leads to invalid JSON structure. Let's break down the correct approach:

1. Ditch Manual JSON Strings: Use Python Dictionaries Instead

Instead of hardcoding a JSON string with escaped characters, represent your data as a native Python dictionary. This is far easier to read, maintain, and ensures your JSON is valid when serialized.

2. Use Locust's Built-in json Parameter for POST Requests

Locust's HTTP client has a json parameter that handles two critical things automatically:

  • Serializes your Python dictionary into a valid JSON string
  • Sets the correct Content-Type: application/json header (which most APIs require to parse the payload correctly)

Corrected Code Example

Here's how to rewrite your task using this approach:

from locust import HttpUser, TaskSet, task  # Note: HttpLocust is deprecated in Locust 1.x+; use HttpUser instead

class UserBehavior(TaskSet):
    @task
    def submit_account_inquiry(self):
        # Define your payload as a Python dictionary (match the structure your API expects)
        payload = [
            {
                "data": {
                    "Account Number": "1234567898",
                    "Bank Code": "EBN",
                    "AppId": "com.appzonegroup.zone",
                    "deviceId": "your_device_id_value"  # Fill in your actual device ID here
                    # Add any other required fields your API expects
                }
            }
        ]
        
        # Send the POST request using the json parameter
        response = self.client.post(
            "/your-api-endpoint-path",  # Replace with your actual API endpoint URL
            json=payload
        )
        
        # Optional: Debugging to check response details if errors persist
        if response.status_code >= 400:
            print(f"Request failed! Status: {response.status_code}, Response: {response.text}")

class WebsiteUser(HttpUser):
    tasks = [UserBehavior]
    min_wait = 5000  # Minimum wait time between tasks (ms)
    max_wait = 9000  # Maximum wait time between tasks (ms)

Why This Works

  • Valid JSON: By using a Python dict and letting Locust handle serialization, you eliminate typos or missing quotes that break your JSON structure.
  • Correct Headers: The json parameter automatically sets the Content-Type header to application/json, which tells the server to parse the payload as JSON (a common cause of Bad Requests if missing).

If for some reason you need to work with a pre-built JSON string, ensure it's valid and explicitly set the Content-Type header:

import json

valid_json_str = json.dumps(payload)  # Use json.dumps on your dict to get a valid string
response = self.client.post(
    "/your-endpoint",
    data=valid_json_str,
    headers={"Content-Type": "application/json"}
)

Quick Debugging Tips

  • Double-check that your payload structure (like the outer list in your example) matches exactly what the API expects.
  • Verify all required fields are present and correctly named (API endpoints are often case-sensitive).
  • Test the payload first with tools like Postman—if it works there, replicate the exact structure in your Locust code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:24:59