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

It's weird, i tried postman or browser, http get request works fine, but it aways get status: 400

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745660329a4638795.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信