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

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 async with .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/html response and empty body instead of the expected application/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

  1. Uri.parse() for URLs: The http package works more reliably with Uri objects than raw strings, eliminating potential parsing bugs.
  2. Added Accept header: Explicitly telling the server you expect JSON ensures it doesn’t default to text/html for error or unrecognized requests.
  3. Switched to await: This makes your async code more readable and ensures you wait for the full response before proceeding, avoiding race conditions.
  4. Error handling: The try/catch block 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 empty text/html response.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:04:34