【问题标题】:http.post return 307 error code in flutterhttp.post在flutter中返回307错误代码
【发布时间】:2020-04-08 19:27:56
【问题描述】:

我正在使用http客户端进行flutter网络调用。

  1. 我的请求正在处理邮递员,得到正确响应,
  2. 但在尝试使用 http.post 时,它返回错误代码 307-临时重定向,

方法体:

static Future<http.Response> httpPost(
  Map postParam, String serviceURL) async {
Map tempParam = {"id": "username", "pwd": "password"};
var param = json.encode(tempParam);
serviceURL = "http:xxxx/Login/Login";

// temp check
Map<String, String> headers = {
  'Content-Type': 'application/json',
  'cache-control': 'no-cache',
};
await http.post(serviceURL, headers: headers, body: param).then((response) {
  return response;
});
}

此外,相同的代码会返回对其他请求和 URL 的正确响应。 首先我尝试使用 chopper 客户端,但遇到了同样的问题。

我无法从服务器端检测到该问题。

任何帮助/提示都会有所帮助

【问题讨论】:

    标签: flutter


    【解决方案1】:

    尝试在serviceUrl 的末尾加上一个斜杠/。所以,serviceUrl 是serviceURL = "http:xxxx/Login/Login/" 而不是serviceURL = "http:xxxx/Login/Login"

    这对我有用。

    【讨论】:

    • 这个解决了我 2 小时寻找解决方案的过程。谢谢。
    【解决方案2】:

    您需要找到一种方法来跟随重定向

    也许邮递员正在这样做。

    阅读全文>> https://api.flutter.dev/flutter/dart-io/HttpClientRequest/followRedirects.html

    您可以尝试使用get 代替post 吗?至少尝试看看发生了什么

    在文档中说:

    Automatic redirect will only happen for "GET" and "HEAD" requests
    only for the status codes 
    
    HttpStatus.movedPermanently (301), 
    HttpStatus.found (302), 
    HttpStatus.movedTemporarily (302, alias for HttpStatus.found), 
    HttpStatus.seeOther (303),
    HttpStatus.temporaryRedirect (307)
    

    【讨论】:

      【解决方案3】:

      在 URL 中保留 https 而不是 http 对我有帮助。

      【讨论】:

        【解决方案4】:

        @Abel 上面的回答是正确的,但我不得不改用:

        Uri url = Uri.https(defaultUri, path);

        Uri url = Uri.parse('https://todo-fastapi-flutter.herokuapp.com/plan/');

        plan 之后得到最后一个/

        第一种方法一直丢弃它,所以我得到了 307 错误。

        flutter.dev 展示了一个完整的例子:

        Future<http.Response> createAlbum(String title) {
          return http.post(
            Uri.parse('https://jsonplaceholder.typicode.com/albums'),
            headers: <String, String>{
              'Content-Type': 'application/json; charset=UTF-8',
            },
            body: jsonEncode(<String, String>{
              'title': title,
            }),
          );
        }
        

        这里:https://flutter.dev/docs/cookbook/networking/send-data#2-sending-data-to-server

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-04
          • 2017-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多