为什么我的POST请求仅对我的API不起作用?

时间:2020-08-07 21:06:04

标签: api flutter post

我已经在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."}

enter image description here

enter image description here

我包括的是这些。

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);
    }

1 个答案:

答案 0 :(得分: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);