Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my POST request not working in flutter for my API only?

Tags:

post

flutter

I've written a code for an API POST request in flutter which is not working in the app, however, same code with https://jsonplaceholder.typicode.com/ is working.

Here's the code for my project.(NOT WORKING)

  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": "[email protected]", "password": "PASSWORD_HERE"});
    http.Response response = await http.post(apiUrl,headers: headers, body: json);
    var jsonResponse = convert.jsonDecode(response.body);
    print(jsonResponse);
  }

always returns following response.

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

and jsonplaceholder.typeicode.com code goes like this. (WORKING FINE)

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

always returns

{id: 101}

But in postman app, its working fine. here's the raw output.

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"

[email protected]
----------------------------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

my includes are these.

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

I'm unable to figure out what's the issue. I've tried changing the contentType to almost every possible value.

Please let me know if any further detail is needed.

Flutter Doctor output.

[√] 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 code is as follows.

     /* 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);
    }
like image 483
GoharSahi Avatar asked Dec 06 '25 14:12

GoharSahi


1 Answers

1) Wrong Url

In flutter you are using URL:

.../api_daily_logs/user/login

but in Postman:

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

After changing URL in to signIn, response (.json) it's different:

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

2) Fix body

Firstly - do not encode this map, so change from:

final json = convert.jsonEncode({
  "email": "[email protected]",
  "password": "PASSWORD_HERE",
});

to:

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

final json = {
  "email": "[email protected]",
  "password": "PASSWORD_HERE",
};

Secondly - remove headers, because If body is a Map the content-type of the request will be set to "application/x-www-form-urlencoded"

Working code

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

final json = {
  "email": "[email protected]",
  "password": "PASSWORD_HERE"
};

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

var jsonResponse = jsonDecode(response.body);
print(jsonResponse);
like image 162
Boken Avatar answered Dec 08 '25 16:12

Boken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!