【问题标题】:Why is my POST request not working in flutter for my API only?为什么我的 POST 请求仅对我的 API 不起作用?
【发布时间】:2020-11-28 05:23:01
【问题描述】:

我已经为 Flutter 中的 API POST 请求编写了一个代码,该代码在应用程序中不起作用,但是,与 https://jsonplaceholder.typicode.com/ 相同的代码正在运行。

这是我的项目的代码。(不工作

  Future<void> _doSignIn() async {
    String apiUrl = "http://prelive.sewer-viewer.com/api_daily_logs/user/signIn";
    Map<String, String> headers = {"Content-type": "multipart/form-data"};
    final json =  convert.jsonEncode({"email": "EMAILADDRESS@GMAIL.COM", "password": "PASSWORD_HERE"});
    http.Response response = await http.post(apiUrl,headers: headers, body: json);
    var jsonResponse = convert.jsonDecode(response.body);
    print(jsonResponse);
  }

总是返回以下响应。

{
  "status": 0,
  "msg": "userToken: , status: 0, msg: Invalid username and/or password. Please try again"
}

和 jsonplaceholder.typeicode.com 的代码是这样的。 (工作正常

  Future<void> _doSignIn() async {
    Map<String, String> header = {"Content-type": "multipart/form-data"};
    String testUrl = "https://jsonplaceholder.typicode.com/posts";
    final test = convert.jsonEncode({
      "userId": 11,
      "title": "Test Title",
      "body": "Test Body Test Body Test Body Test Body Test Body Test Body Test Body Test Body Test Body Test Body "
    });
    http.Response resp = await http.post(testUrl,headers: header, body: test);
    var jsonResp = convert.jsonDecode(resp.body);
    print(jsonResp);

总是返回

{id: 101}

但在邮递员应用程序中,它工作正常。这是原始输出。

POST /api_daily_logs/user/signIn HTTP/1.1
User-Agent: PostmanRuntime/7.26.2
Accept: */*
Postman-Token: b60ecfe7-7ccb-44bd-93f8-d95995bc5eb8
Host: prelive.sewer-viewer.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------071795598422914636012534
Content-Length: 304
----------------------------071795598422914636012534
Content-Disposition: form-data; name="email"

EMAILADDRESS@GMAIL.COM
----------------------------071795598422914636012534
Content-Disposition: form-data; name="password"

PASSWORD_HERE
----------------------------071795598422914636012534--
HTTP/1.1 200 OK
Date: Fri, 07 Aug 2020 20:38:13 GMT
Server: Apache
X-Powered-By: PHP/7.1.33
Status: 200
Content-Length: 405
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
{"userToken":"eyJ0eXAiOiJKV1QiLCiOjE1OTY4MjkxNjUsImp0aSI6InNUWmphR3VaN3p1RTlRPT0iLCJpc3MiOiJwcmVsaXZlLnNld2VyLXZpZXdlci5jb20iLCJuYmYiOjE1OTY4cCI6MTSFDGSDF9070SDFLK8LK78L7KGDFL5LLK54SI6eyJ1c2VySWQiOiIxMDE0IiwidXNlck5hbWUiOiJheml6YV9hcGlAY2FsbS1zb2xASDFSFA89ASDF._mLNOkKJHKkjkj34tcluD1w8w","status":1,"msg":"User authentication has been successfully processed."}

我的包括这些。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

我无法弄清楚是什么问题。我已经尝试将 contentType 更改为几乎所有可能的值。

如果需要任何进一步的细节,请告诉我。

Flutter Doctor 输出。

[√] Flutter (Channel stable, v1.17.0, on Microsoft Windows [Version 10.0.18362.959], locale en-US)
    • Flutter version 1.17.0 at F:\flutter-sdk
    • Framework revision e6b34c2b5c (3 months ago), 2020-05-02 11:39:18 -0700
    • Engine revision 540786dd51
    • Dart version 2.8.1


[√] Android toolchain - develop for Android devices (Android SDK version 30.0.1)
    • Android SDK at C:\Users\MRCOM\AppData\Local\Android\Sdk
    • Platform android-30, build-tools 30.0.1
    • ANDROID_HOME = C:\Users\MRCOM\AppData\Local\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Android Studio (version 4.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 48.0.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code (version 1.47.3)
    • VS Code at C:\Users\MRCOM\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.13.1

[√] Connected device (1 available)
    • sdk gphone x86 • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)

• No issues found!

API代码如下。

     /* signIn
     *
     * This function will used to verify user login detail and provide an access token which will contains token
     * expiration and other user detail.
     *
     * This function also update user API key in app_users table which will later use to verify user authentication.
     *
     * @author Usman
     */
public function signIn_post(){
        //---- variables
        $response_array = array('userToken'=> '', 'status'=>0, 'msg' => $this->lang->parseLine('invalid_detail'));
        $isValidToken = false;

        //---- posted arguments
        $post = $this->input->post();
        $email = !empty($post['email']) ? trim($post['email']) : '';
        $password = !empty($post['password']) ? trim($post['password']) : '';

        //---- if an email or password is empty then return an error message
        if($email == '' || $password == ''){
            header('WWW-Authenticate: Basic realm="REST API Required username:password"');
        }
        else {
            //---- validate login detail
            $apiUserData = $this->user_model->loginAuthentication($email, $password);

            //---- if user data found then generate access token and update in DB
            if(!empty($apiUserData)){
                //---- verify that user is already logged in and don't have password expired
                if(!empty($apiUserData['dailyLogApiKey'])){
                    $isValidToken = $this->authorization_server->isValidToken($apiUserData['dailyLogApiKey']);
                }

                if(!$isValidToken){
                    $tokenData = array();
                    $tokenData['id'] = $apiUserData['userID'];
                    $tokenData['username'] = $apiUserData['email'];
                    $token = $this->authorization_server->generateToken($tokenData, CLIENT_SECRET_CODE);

                    //---- update newly access token in DB
                    $this->user_model->updateKeyAuthentication($apiUserData['userID'], $token);

                    //---- update sign in user ID in API Call Log
                    $this->user_model->updateSignInApiCallLog($apiUserData['userID']);
                }
                else{
                    $token = $apiUserData['dailyLogApiKey'];
                }

                //---- update response array
                $response_array['userToken'] = $token;
                $response_array['status'] = 1;
                $response_array['msg'] = $this->lang->parseLine('successful_login');

                $this->response($response_array, 200);
            }
        }

        //---- Authentication Failed
        $this->response($response_array, 401);
    }

【问题讨论】:

  • 这可能是你的 API 的问题,它需要一个令牌,你能分享你的 api 代码吗?
  • 因为它说它需要一个头文件格式来授权
  • @ParitoshYadav,没有明白你所说的头文件格式的意思。你能详细说明一下吗?
  • 我的意思是在标头中使用令牌进行授权
  • 你可以在邮递员中看到他们提供的令牌

标签: api flutter post


【解决方案1】:

1) 网址错误

在颤振中你使用的是 URL:

.../api_daily_logs/user/login

但在邮递员中:

.../api_daily_logs/user/signIn
                          ^
                          |
                  this part is different

将 URL 更改为 signIn 后,响应 (.json) 不同了:

{
    "userToken": "",
    "status": 0,
    "msg": "Invalid username and/or password. Please try again"
}

2) 修复主体

首先 - 不要对这个地图进行编码,所以从:

final json = convert.jsonEncode({
  "email": "EMAILADDRESS@GMAIL.COM",
  "password": "PASSWORD_HERE",
});

到:

// It's just Map<String, String>

final json = {
  "email": "EMAILADDRESS@GMAIL.COM",
  "password": "PASSWORD_HERE",
};

其次 - 删除标头,因为如果 bodyMap,则请求的内容类型将设置为 "application/x-www-form-urlencoded"

工作代码

String apiUrl = "http://prelive.sewer-viewer.com/api_daily_logs/user/signIn";

final json = {
  "email": "EMAILADDRESS@GMAIL.COM",
  "password": "PASSWORD_HERE"
};

http.Response response = await http.post(apiUrl, body: json);

var jsonResponse = jsonDecode(response.body);
print(jsonResponse);

【讨论】:

  • 是的....我也想过..如果你没有发布答案,我会自己回答。
  • 但问题可能是其他问题......因为它使用相同的用户名/密码通过邮递员登录,所以为什么不没有它。
  • @GoharSahi 什么/哪里有问题?还是不行?
  • 是的,它不起作用。当我从邮递员应用程序登录时,它可以工作..但是当我从颤振登录时,它不起作用。使用相同的用户名/密码。
  • it doesn't work 是什么意思?错误的答案?当我使用上面的代码接收Invalid username and/or password. Please try again 时,它就像在邮递员中一样。你的回应是什么?
猜你喜欢
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 2012-02-13
  • 1970-01-01
  • 2021-11-12
  • 2021-08-31
相关资源
最近更新 更多