Flutter使用Google API发送邮件时遇400解析错误求助
Hey there! Let's get this sorted out quickly. That 400 error is spelling out exactly what's going wrong: the API you're calling only accepts JSON-formatted request bodies, but your POST request is sending form-encoded data (the default behavior for many HTTP clients if you don't specify otherwise).
Here's how to fix it step by step:
Set the correct
Content-Typeheader
Your request must include the headerContent-Type: application/json— this tells the server to expect JSON data instead of standard form fields.Convert your request body to a valid JSON string
Instead of passing key-value pairs as form data, serialize your payload into a proper JSON string. For example, if you're using JavaScript:// Correct implementation fetch('your-target-api-url', { method: 'POST', headers: { 'Content-Type': 'application/json', // Add any other required headers (like auth tokens) here }, body: JSON.stringify({ // Your request data structured as JSON scope: 'send-email', recipient: 'user@example.com', subject: 'Test Email' }) })Validate your JSON syntax
Since you mentioned uncertainty about your JSON format, use a free tool like JSONLint to check for syntax errors (missing commas, unclosed quotes, mismatched brackets, etc.). Even a tiny typo here will cause parsing failures.
Quick troubleshooting checks:
- If you're using tools like Postman, make sure you've selected the "raw" body type and set the format dropdown to JSON (not form-data or x-www-form-urlencoded).
- Avoid mixing form data and JSON — don’t use
FormDataobjects alongsideJSON.stringifyin the same request. - Double-check your API docs to confirm it explicitly accepts JSON payloads (most modern APIs do, but it’s always good to verify).
内容的提问来源于stack exchange,提问作者rafaelcb21

