最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

flutter - HTTP request get statusCode:400 in flutter_test, but it get status:200 in orignal dart method call - Stack Overflow

matteradmin4PV0评论

It's weird, i tried postman or browser, http get request works fine, but it aways get status: 400 in flutter. I just only debug it on web(chrome) Simulator and flutter-test.

Here is my env:

Flutter (Channel stable, 3.24.3, on macOS 15.1 24B83 darwin-arm64
Dart version 3.5.3
DevTools version 2.37.3

Here is the minimized code.

  Future<String> httpget( String urlStr, String path, Map<String, dynamic> params) async {
    try {
      var url = Uri.https(urlStr, path);
      var response = await http.get(url);
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');
      print('Response header: ${response.headers}');

      return response.body;
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }

  Future<String> dioget(String url, Map<String, dynamic> params) async {
    try {
      var dio = Dio();
      dio.interceptors.add(LogInterceptor());
      Response response = await dio.get(
        url,
        queryParameters: params,
        options: Options(
          validateStatus: (int? status) {
            return status != null;
          },
        ),
      );
      return response.data;
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }

  test('network test', () async {
    // http package
    String url = "httpbin";
    String path = "get";
    await httpget(url, path, {}).then((response) {
      print(response);
    });

    // dio package
    await dioget(";, {}).then((response) {
      print(response);
    });
  });
}

output:


*** Response ***
uri: 
statusCode: 400
headers:

I can open this link in chrome or postman.


I put this dio get request on a Text widget, i think it's ok.

But still, flutter-test doesn't work.

class Header extends StatelessWidget {
  const Header({Key? key}) : super(key: key);
  Future<String> dioget(String url, Map<String, dynamic> params) async {
    try {
      var dio = Dio();
      dio.interceptors.add(LogInterceptor());
      Response response = await dio.get(
        url,
        queryParameters: params,
        options: Options(
          validateStatus: (int? status) {
            return status != null;
          },
        ),
      );
      return response.data["url"];
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }
  @override
  Widget build(BuildContext context) =>
      Container(
        color: Colors.red.withOpacity(0.5),
        child: FutureBuilder<String>(
          future: dioget(";, {"test": "test"}),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return Text(snapshot.data ?? 'No data');
            }
          },
        ),
      );
}

It's weird, i tried postman or browser, http get request works fine, but it aways get status: 400 in flutter. I just only debug it on web(chrome) Simulator and flutter-test.

Here is my env:

Flutter (Channel stable, 3.24.3, on macOS 15.1 24B83 darwin-arm64
Dart version 3.5.3
DevTools version 2.37.3

Here is the minimized code.

  Future<String> httpget( String urlStr, String path, Map<String, dynamic> params) async {
    try {
      var url = Uri.https(urlStr, path);
      var response = await http.get(url);
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');
      print('Response header: ${response.headers}');

      return response.body;
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }

  Future<String> dioget(String url, Map<String, dynamic> params) async {
    try {
      var dio = Dio();
      dio.interceptors.add(LogInterceptor());
      Response response = await dio.get(
        url,
        queryParameters: params,
        options: Options(
          validateStatus: (int? status) {
            return status != null;
          },
        ),
      );
      return response.data;
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }

  test('network test', () async {
    // http package
    String url = "httpbin.";
    String path = "get";
    await httpget(url, path, {}).then((response) {
      print(response);
    });

    // dio package
    await dioget("http://httpbin./get", {}).then((response) {
      print(response);
    });
  });
}

output:


*** Response ***
uri: http://httpbin./get
statusCode: 400
headers:

I can open this link in chrome or postman. http://httpbin./get


I put this dio get request on a Text widget, i think it's ok.

But still, flutter-test doesn't work.

class Header extends StatelessWidget {
  const Header({Key? key}) : super(key: key);
  Future<String> dioget(String url, Map<String, dynamic> params) async {
    try {
      var dio = Dio();
      dio.interceptors.add(LogInterceptor());
      Response response = await dio.get(
        url,
        queryParameters: params,
        options: Options(
          validateStatus: (int? status) {
            return status != null;
          },
        ),
      );
      return response.data["url"];
    } catch (e) {
      print('Error: $e');
      throw e;
    }
  }
  @override
  Widget build(BuildContext context) =>
      Container(
        color: Colors.red.withOpacity(0.5),
        child: FutureBuilder<String>(
          future: dioget("https://httpbin./get", {"test": "test"}),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return Text(snapshot.data ?? 'No data');
            }
          },
        ),
      );
}

Share Improve this question edited Nov 22, 2024 at 6:54 Kyrie Cui asked Nov 16, 2024 at 10:54 Kyrie CuiKyrie Cui 112 bronze badges 9
  • import 'package:http/http.dart' as http; void main() async { var url = Uri.https('httpbin.', 'put'); var response = await http.put(url, body: {'foo': 'bar'}); print(response.statusCode); print(response.body); print('======================='); url = Uri.https('httpbin.', 'get'); response = await http.get(url); print(response.statusCode); print(response.body); } – pskink Commented Nov 16, 2024 at 11:11
  • it all works. status:200 – Kyrie Cui Commented Nov 16, 2024 at 11:13
  • yes, i know ;-) – pskink Commented Nov 16, 2024 at 11:16
  • It maybe something getwrong on flutter-test?? – Kyrie Cui Commented Nov 16, 2024 at 11:28
  • no, your code was wrong a little bit – pskink Commented Nov 16, 2024 at 11:40
 |  Show 4 more comments

1 Answer 1

Reset to default 0

It seems like CORS error, This issue is only with Flutter web: https://github/cfug/dio/issues/2026.

Here is the solution: How to solve flutter web api cors error only with dart code?

Post a comment

comment list (0)

  1. No comments so far