Flutter/Dart嵌套JSON的HTTP POST请求响应异常排查求助
Fixing Your Flutter HTTP POST Request with Nested JSON
Let’s work through this issue step by step to get your request returning the expected JSON response.
Key Issues in Your Current Code
- You’re mixing
asyncwith.then()without properly handling the async flow, which can lead to unforeseen behavior. - While your nested JSON structure looks correct, the server isn’t recognizing your request properly—hence the
text/htmlresponse and empty body instead of the expectedapplication/json.
Corrected Code
Here’s a revised version of your function with proper async handling and request formatting:
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; Future<http.Response> postRequest() async { // Parse the URL into a Uri object (more reliable than raw strings) final url = Uri.parse('https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate'); // Your nested JSON body remains unchanged—this structure is correct final body = jsonEncode({ 'data': { 'apikey': '12345678901234567890' } }); print("Body: $body"); try { final response = await http.post( url, headers: { "Content-Type": "application/json", // Explicitly tell the server you expect JSON in return "Accept": "application/json", }, body: body, ); // Log detailed response info for debugging print("Response status: ${response.statusCode}"); print("Response body: ${response.body}"); print("Response headers: ${response.headers}"); print("Response request: ${response.request}"); return response; } catch (e) { print("Request failed: $e"); rethrow; // Pass the error up for upstream handling if needed } }
What Changed & Why
Uri.parse()for URLs: Thehttppackage works more reliably withUriobjects than raw strings, eliminating potential parsing bugs.- Added
Acceptheader: Explicitly telling the server you expect JSON ensures it doesn’t default totext/htmlfor error or unrecognized requests. - Switched to
await: This makes your async code more readable and ensures you wait for the full response before proceeding, avoiding race conditions. - Error handling: The
try/catchblock helps catch network issues or server errors that might be causing the empty response.
Additional Troubleshooting Tips
- Double-check your
apikey: An invalid or expired key could trigger a silent error from the server, resulting in an emptytext/htmlresponse. - Test with curl/Postman: Verify the request works outside Flutter to rule out server-side issues. Example curl command:
curl -X POST https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -d '{"data": {"apikey": "12345678901234567890"}}' - Check for required headers: Some APIs require additional headers like
User-Agent—if the curl request works but Flutter doesn’t, try adding this header to your request.
If the curl request returns the expected JSON, the issue was in your Flutter code’s request handling. If not, you’ll need to confirm valid credentials or additional requirements with the API provider.
内容的提问来源于stack exchange,提问作者n8bour
相关产品推荐
相关产品推荐

