Git Product home page Git Product logo

requests's Introduction

banner-01

Version License

a dart library to make HTTP requests (inspired by python requests module). It comes with JSON support and a lightweight implementation to store cookies like a browser.

Cookies, huh?

Server side cookies (via response header SET-COOKIE) are stored using the assistance of quiver.cache. Stored cookies will be send seamlessly on the next http requests you make to the same domain (simple implementation, similar to a web browser).

Install

Add this to your package's pubspec.yaml file:

dependencies:
  requests: ^4.8.0-alpha.0

Usage

Start by importing the library

import 'package:requests/requests.dart';

Let's make a simple HTTP request

var r = await Requests.get('https://google.com');
r.raiseForStatus();
String body = r.content();

the Response object

just like in python's request module, the Response object has this functionality

  • r.throwForStatus() - will throw an exception if the response statusCode is not a great success.
  • r.raiseForStatus() - same as throwForStatus
  • r.statusCode - the response status code
  • r.url - the url in the request
  • r.headers - the response headers
  • r.success - a boolean. true indicates that the request was a great success
  • r.hasError - a boolean. true indicates that the request was not a great success
  • r.bytes() - return the body in the response as a list of bytes
  • r.content() - return the body in the response as a string
  • r.json() - recodes the body in the response and returns the result (dynamic type)

Optional Arguments

  • json - a dynamic object that will be json encoded and then be set as the request's body
  • body - a raw string to be used as the request's body
  • bodyEncoding - default RequestBodyEncoding.FormURLEncoded. will set the content-type header
  • headers - Map<String, String> of custom client headers to add in the request
  • timeoutSeconds - default 10 seconds. after that period of time without server response an exception is thrown
  • persistCookies - default true. if should respect server's command to persist cookie
  • verify - default true. if the SSL verification enabled
  • withCredentials - default false. for dart web to handle cookies, authorization headers, or TLS client certificates

Note: Only one optional argument can be used in a single request body or json

Class Methods

  • .clearStoredCookies(url) - clears the stored cookies for the url
  • .setStoredCookies(url, CookieJar) - set the stored cookies for the url
  • .getStoredCookies(url) - returns a CookieJar of the stored cookies for the url
  • .addCookie(url, name, value) - add a Cookie to the CookieJar associated to the url

Examples

HTTP post, body encoded as application/x-www-form-urlencoded, parse response as json

var r = await Requests.post(
  'https://reqres.in/api/users',
  body: {
    'userId': 10,
    'id': 91,
    'title': 'aut amet sed',
  },
  bodyEncoding: RequestBodyEncoding.FormURLEncoded);

r.raiseForStatus();
dynamic json = r.json();
print(json!['id']);

HTTP delete

var r = await Requests.delete('https://reqres.in/api/users/10');
r.raiseForStatus();

Ignore SSL self-signed certificate

var r = await Requests.get('https://expired.badssl.com/', verify: false);
r.raiseForStatus();

Play with stored cookies

String url = "https://example.com";
await Requests.clearStoredCookies(url);

// Set cookies using [CookieJar.parseCookiesString]
var cookies = CookieJar.parseCookiesString("name=value");
await Requests.setStoredCookies(url, cookies);

// Add single cookie using [CookieJar.parseCookiesString]
var cookieJar = await Requests.getStoredCookies(url);
cookieJar["name"] = Cookie("name", "value");
await Requests.setStoredCookies(url, cookieJar);

// Add a single cookie using [Requests.addCookie]
// Same as the above one but without exposing `cookies.dart`
Requests.addCookie(url, "name", "value");

More examples can be found in example/.

Business vector created by freepik - www.freepik.com

requests's People

Contributors

anirudh24seven avatar baskar007 avatar eggate avatar filledstacks avatar frederikpietzko avatar gabrieltavernini avatar genesiscz avatar ianmaciel avatar imdatsolak avatar jossef avatar juvs avatar lehoanglong avatar marcodigioia avatar obuhovsergai avatar rafaelcmm avatar reddwarf03 avatar sehnryr avatar tlkops avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

requests's Issues

create function to manually add cookies

in the past we could add cookies via:

Future<void> addCookieToRequests(String name, String value) async {
  final Map<String, String> savedCookies = await Requests.getStoredCookies(Requests.getHostname(serviceUrl));
  savedCookies[name] = value;
  await Requests.setStoredCookies(Requests.getHostname(serviceUrl), savedCookies);
}

now the working solution is more complex:

// ignore: implementation_imports
import 'package:requests/src/cookie.dart';
...
Future<void> addCookieToRequests(String name, String value) async {
  final CookieJar cookieJar = await Requests.getStoredCookies(Requests.getHostname(serviceUrl));
  cookieJar.delegate[name] = Cookie(name, value);
  await Requests.setStoredCookies(Requests.getHostname(serviceUrl), cookieJar);
}

if instead Requests exposed a function to add cookies this could be simplified to something like:
Requests.addCookie(String url, String name, dynamic value);

in this way we would not have any need to expose the cookies.dart file as well as having a clean handling of cookies.

Flutter Web not working (HttpClient not found)

Describe the bug
I use your Libary for request/login to my backend. On Windows Desktop and Android everything works fine, but as soon as I want to build my app for Web I get the error shown below.

I tried to use import 'package:universal_io/io.dart'; for fixing it, but That only fixes the HttpClient error not the IOClient.

Please fix!

Error

Launching lib\main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome...
/C:/Users/LD/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/requests-4.3.0/lib/src/requests.dart:244:22: Error: Method not found: 'HttpClient'.
      var ioClient = HttpClient();
                     ^^^^^^^^^^
/C:/Users/LD/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/requests-4.3.0/lib/src/requests.dart:246:16: Error: Method not found: 'IOClient'.
      client = IOClient(ioClient);
               ^^^^^^^^
Failed to compile application.

To Reproduce
Steps to reproduce the behavior:

  1. Build App with "Chrome(web)" device (Flutter)

Expected behavior
No errors and working build

Desktop

  • Browser (Chrome & Edge) on WIndows

Response and Request interceptor

I think we need feature like this here.
I am enjoying this lib but I would love to handle all 401 or 500 in one place but I seems is very hard. Having this kind of feature can help since all requests and response pass certain point.

About _extractResponseCookies

Today, I test requests for request django LoginView, the login success response 302 and the responseHeaders like:

{set-cookie: csrftoken=JXbDPUlqe3pJCxC3EHib4HT52WIFtpKeS63qsYMyehcVocrWUMIZeleUmBx1IZBj; expires=Wed, 06 Jan 2021 21:21:58 GMT; Max-Age=31449600; Path=/; SameSite=Lax,sessionid=58zhlb01kfqoa528efxpr4o75b02x76j; expires=Wed, 22 Jan 2020 21:21:58 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax, location: /, cache-control: max-age=0, no-cache, no-store, must-revalidate, private, date: Wed, 08 Jan 2020 21:21:58 GMT, vary: Cookie, content-length: 0, x-frame-options: DENY, content-type: text/html; charset=utf-8, x-content-type-options: nosniff, server: WSGIServer/0.2 CPython/3.7.6, expires: Wed, 08 Jan 2020 21:21:58 GMT}

I found SameSite=Lax,sessionid=58zhlb01kfqoa528efxpr4o75b02x76j;, and parser result not contains sessionid,only csrftoken=JXbDPUlqe3pJCxC3EHib4HT52WIFtpKeS63qsYMyehcVocrWUMIZeleUmBx1IZBj

Is this a django bug? or a requrests _extractResponseCookies bug?

Cookies are ignored on redirects

Hi, it appears that this library ignores the cookies provided by the Set-Cookie header in a 301/302 redirect.

My best guess as to what's causing this: when Dart's HTTP library has followRedirects = true, ONLY the headers from the final destination are returned, meaning the headers from the prior responses are totally lost. โ˜น๏ธ

Possible workaround could be:

  1. Use final request = Request(...) for all methods
  2. Set request.followRedirects = false
  3. Do var response = _handleHttpResponse(...) before return
  4. Check if response.statusCode is 301/302. If true: Set response = _httpRequest(HttpMethod.GET, response.headers['location'], ...)
  5. return response

Response History Feature Request

Hi,

It would be nice if, like Python's requests library, the Response class had a property history that would be a list of all the requests the client made to get to that response i.e a log of the redirects that the client automatically made. On that note, a parameter like followRedirects added to the .get and .post methods would be helpful

Dart command get error

I want to test the package by dart main.dart

import 'package:requests/requests.dart';
import 'package:shared_preferences/shared_preferences.dart';
import "package:test/test.dart";

main() async {
  var r = await Requests.get("https://google.com");
  r.raiseForStatus();
  String body = r.content();
  print(body);
}

error:

 Error: Not found: 'dart:ui'

Can you create example project on github?

setstoredcookies using cookiejar

Hey, there's an issue when I follow the example of storing cookies. In the example, the parameter of setStoredCookies(String hostname, Map<String, String> cookies). But when I try to follow it, the parameter is setStoredCookies(String hostname, CookieJar cookies). Did I use a different version of the library or the example is not updated yet? Thanks!

image

Send a List in a POST request

I need to post an object array ([{}, {}]) to my node.js server, something similar to this:

final List<Map<String, dynamic>> a = [
  {'a': 'b'}
];

final response = await Requests.post(
  API_URL,
  json: a,
  headers: HEADERS
);

However, the json parameter of the post method asks for Map<String, dynamic>, returning the following error:
The argument type 'List<Map<String, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.

Any thoughts on this?
Thank you!

CookieJar is not exposed

If you use Requests.getStoredCookies() it return a Future CookieJar, but CookieJar is not exposed.

library requests;

export 'src/requests.dart';
export 'src/response.dart';
export 'src/cookie.dart';

As a workaround we need to import the specify source, but we get a warning from Dart.

image

_extractCookies when cookie has an equal sign

We are using requests to handle our flutter http and found an issue in extractCookies. When a response cookie has an equals sign it, the existing split on "=" causes us to lose a portion of our cookie. IE

cookie1=qwerty-=?!2345

breaks into three parts

  1. cookie1
  2. qwerty-
  3. ?!2345

to work through this locally we are now splitting on the first instance of an =.

crash in getStoredCookies, calling fromJson with null

Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null.
Receiver: null
Tried calling: length)

static Future<Map<String, String>> getStoredCookies(String hostname) async {
    try {
      String hostnameHash = Common.hashStringSHA256(hostname);
      String cookiesJson = await Common.storageGet('cookies-$hostnameHash');


   // first launch cookiesJson is null, but you are calling fromJson below will null


      var cookies = Common.fromJson(cookiesJson);
      return Map<String, String>.from(cookies);
    } catch (e) {
      log.shout(
          "problem reading stored cookies. fallback with empty cookies $e");
      return Map<String, String>();
    }
  }

does not save cookies in the release.

Good afternoon, tell me what the problem may be. Everything works on the emulator and when testing on the device, but if you throw the APK file to the device and install it, the requests go away, but from different sessions. At the same time, everything is fine on ios, only on android there is such a problem.

no longer handling list of strings as a single queryParam

i'm not 100% sure, but it looks like something between 3.1.0 and 3.3.0 somehow broke being able to pass query parameters as a list:

eg
Map<String, dynamic> queryParams = {
keyOne: "valueOne",
keyTwo: "valueTwo",
keyThree: [valueThree, valueFour, valueFive]
};

feel free to tell me i'm wrong as i haven't been able to get my call working even if i change it to Map<String, dynamic> queryParams = {
keyOne: "valueOne",
keyTwo: "valueTwo",
keyThree: "valueThree&keyThree=valueFour&keyThree=valueFive"
};

Remove httponly from cookie when making HTTP call using Flutter

I have an Express application that has a cookie-based authenticated route. I am using cookie-session to store auth tokens in the cookie.

I am developing a mobile app using Flutter and am using the requests package to manage cookies while making HTTP calls. I am able to make basic HTTP GET and POST calls.

My Express application has two routes - Sign In and Get Info. The route to Sign In authenticates the user and sets an auth token in the cookie using cookie-session. The Get Info gets information for an authenticated user, and the authentication is checked by a middleware.

The Express application is working as expected when I make calls using Postman or curl but is failing when I make calls using Flutter.

When I analysed the differences, I found that the Flutter application is adding an 'httponly' in the cookie, and consequently, the auth tokens are not being extracted. When making the same call using curl, it failed with httponly and worked when I removed the httponly flag in the cookie.

I tried toggling httponly in cookie-session by using sessionOptions and it has not worked.

I am not sure if this is a problem with the serverside code or the clientside code - Could you help me understand if there is a flag that I need to toggle or get around this?

cannot retrieve multiple 'set-cookies'

hey, im having a hard time to retrieve multiple 'set-cookies' from my API. as illustrated below, the Postman is receiving 2 'set-cookies' but the Requests can only retrieve 1. is there any workaround on this? thank you!

Future<LoginModel> login(String email, String password) async {
  final uri = _baseUrl + "/login";
  Map<String, String?> body = {
    'email': email,
    'password': password,
  };
  final response = await Requests.post(uri, body: body, persistCookies: true);
  if (response.success) {
    print("success");
  
    //check for cookies
    var cookie = await Requests.getStoredCookies(Requests.getHostname(uri));
    print("cookie length: $cookie");
    print("cookie user: ${cookie["user"]}");
    print("cookie token_id: ${cookie["token_id"]}");
  
    return LoginModel.fromJson(json.decode(response.content()));
  } else {
    print(response.statusCode);
    response.throwForStatus();
    throw Exception('Failed to login');
  }
}
Future<UserModel> getUserDetail() async {
    final uri = _baseUrl + "/user";
    final response = await Requests.get(uri);
    print(response);
    if (response.success) {
      print("success");
      return UserModel.fromJson(json.decode(response.content()));
    } else {
      print(response.statusCode);
      response.throwForStatus();
      throw Exception('Failed to retrieve user info');
    }
  }

image
image

Store cookies after application exit?

Hi, I just want to ask if the current version stores the cookies even after the application exits? or should I use shared preferences to store the cookies and then set the cookies when opening the app again? thanks!

query params typing

Currently, the methods accept Map<String, dynamic> for query params however the uri.replace() method requires that to be Map<String,String>.

Not sure which is preferable but either Requests could own converting to the query params to a Map<String, String> returning some kind exception to the user if the query params can't be mapped or the api could be updated to require a Map<String, String> for the queryParams.

Makes the users life much easier

for example:

await Requests.get('https://google.com', queryParameters: {'id': '1', 'name': 123});

will raise a runtime exception of

type 'int' is not a subtype of type 'Iterable'

Creating a JSON from POST request data

Hello.

I've been struggling with this for a while and couldn't figure it out. When I use your package like this

Requests.post("https://phpcode.eu/test.php", body: {"username": "test", "password": "test"})
    .then((value) { print(value); });

I am having problems with getting the data with a simple PHP script

<?php
print_r($_POST);

It probably does not recognize the POST data in JSON format and prints an empty array. The same goes for $_REQUEST.

However if I replace this line in src/requests.dart

        future = client.post(uri, body: bodyString, headers: headers);

with

        future = client.post(uri, body: body, headers: headers);

and comment out

contentTypeHeader = "application/json";

it properly gives me the data sent

Array
(
    [username] => test
    [password] => test
)

What am I missing or doing wrong?
Thanks for the support, this has been an amazing package!

Drop flutter dependency ?

I really like this library, it really does http requests easy, like in python, but i think it's unnecessary having a flutter dependency.

I would like to use this package in an another package that i am working on, but i don't want it to have a flutter dependency, since this new package doesn't have any UI manipulation or some Android/IOS exclusive functionality.

So, my suggestion is to somehow drop the flutter,logging and shared_preferences dependence, so that the above situation doesn't happen with another developer, improving this package usability.

422 error doesn't throw exception

The following code doesn't throw an exception when returning a 422 HTTP status code.

Is there a way (without having to add the raiseForStatus method afterwards) to catch all the error status codes?
I have about 200 petitions in my application and adding this method in every single one is somewhat repetitive.

await Requests.patch(
    host,
    headers: HEADERS,
    body: body,
    bodyEncoding: RequestBodyEncoding.JSON,
);

Bug since i update requests 3.1.0 to 3.3.0

Hello,
I updated Requests this morning, but since the update, it is impossible for me to connect to my API, I have the impression that there is a problem with cookies. On the other hand by going back to the 3.1.0 no worries everything works perfectly...

Requests on localhost with custom port won'work

Hello,
If I make a request on await Requests.get("http://localhost:1337/pois", json: true); the request will fail
Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 51113
I mention that on that url localhost:1337/pois there is a service that is working and return me a json payload so it's clear that this won't be the problem.

I see in error log attached that port is 51113 can somehow set it custom ?
Can somehow overcome this ?
Many thanks in advance

How to make login validation on Website using this plugin?

I need to send the username and password and submit with the login button of the website itself, after doing this I need to browse some pages to collect the user information, how can I do this with this plugin?

I'm trying this, but not working ๐Ÿ‘

class ImportCEI {

String urlLoginCEI = "https://cei.b3.com.br/CEI_Responsivo/login.aspx";

Future conectarCEI() async {
try {
var r = await Requests.post(
urlLoginCEI,
body: {
'ctl00$ContentPlaceHolder1$txtLogin': 'xxxx',
'ctl00$ContentPlaceHolder1$txtSenha': 'xxxx',
'ctl00$ContentPlaceHolder1$btnLogar': 'submit',
},
queryParameters: {
'ctl00$ContentPlaceHolder1$txtLogin': 'xxxx',
'ctl00$ContentPlaceHolder1$txtSenha': 'xxxx',
'ctl00$ContentPlaceHolder1$btnLogar': 'submit',
},
verify: false,
bodyEncoding: RequestBodyEncoding.FormURLEncoded);

  print("\n\n Retorno: ${r.content()} \n\n");
  r.raiseForStatus();
  dynamic json = r.json();
  print(json);
} catch(e) {
  print("\n conectarCEI Exception: $e ");
}

}
}

support "application/x-www-form-urlencoded"

Add application/x-www-form-urlencoded encoding support in put and post methods for requests having Map object as body.

Add bodyEncoding to the method signature. the default should be BodyEncoding.JSON if not specified

dynamic body = await Requests.post("https://mydomain.com/api/v1/foo", json: true, body: {"foo":"bar"}, 
bodyEncoding: BodyEncoding.FormURLEncoded);

Add Streamed GET request

Hi, I need a streamed GET request as I am using this package in a mobile app and some of the downloads I want to make are too large to fit into RAM for downloading. Anyway, streamed downloading should be available in any case...

Thus, I would like to use the streamed approach: receive chunks and save them off to a file until the request is finished.

I know how to do this myself, so would you prefer me just doing it the way I think it should be done :) or do you have any guidelines what to do and what not to do?

I would fork and send a PR once it works on my side.

Allow passing cipher to Hive store

Follow-up to #1.

The current implementation uses newHiveDefaultVaultStore without passing the encryptionCipher parameter; as far as I can tell this simply stores the cookies in plain text under /tmp/cookievault.hive:

$ strings tmp/cookievault.hive

Hcookies-568e0fc623584e64ca46a227e484848febbadcd1459b0c8d708a9fd4234b0aa2
cookies-568e0fc623584e64ca46a227e484848febbadcd1459b0c8d708a9fd4234b0aa2
creationTime
2022-04-18T20:21:16.354189
accessTime
2022-04-18T20:21:16.354189
updateTime
2022-04-18T20:21:16.354189
value
     "Secret-Token": "<snip>"

Currently the Hive store is static final and cannot be changed by the user:

// Creates a store
static final store = newHiveDefaultVaultStore(path: path);
// Creates a vault from the previously created store
static final vault = store.vault<String>(
name: 'cookieVault',
eventListenerMode: EventListenerMode.synchronous,
);


Since the recent move has been to detach from flutter, I think the glue for storing and providing the encryption key for HiveAesCipher should be left to the user, for example by storing the AES key in flutter_secure_storage. However, for this to be feasible, there should be a way for the user to customize the store before initialization.

[URGENT] 4.6.0 breaks building mobile-only apps

Describe the bug
Please check my comment on your last commit.

4.6.0 breaks building for mobile only platforms by unconditionally importing browser_client.dart, which is available only on web

To Reproduce

  1. Create a mobile-only app
  2. Add requests
  3. import requests in main.dart
  4. Try compiling

Expected behavior
Compile

Desktop (please complete the following information):

  • OS: iOS / Android

Smartphone (please complete the following information):

  • N/A

Additional context

  • Please use conditional import

Dependencies updates

Hello,

Following Flutter 2.0 update, Firebase now depends on http 0.13.0 which conflicts with requests on 0.12.0. Could you please update the dependencies to match more recent packages?
I'm happy to put together a PR.

Error Object on Server Side Error

Error Handling doesn't provide error object returned from server. It's important to parse error message from server. Error message cannot be identified by status code alone.

SSL handshake error on self-signed cert

Hi
Can you provide an example of Self Sign Certification request.
I want to request to a https website, but get following error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error: 
E/flutter (18567): 	CERTIFICATE_VERIFY_FAILED: certificate is not yet valid(handshake.cc:352))

cookies secure has sticked to next key

Hi,

I have tried to used with secure flag. In the cookies, the secure flag sticked to the next flag. So when it returned back to the server, the server will find key"Secure,token_type" instead of key"token_type"

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0QHRlc3QuY29tIiwiZXhwIjoxNTk5MjgwNzM5fQ.DiJ0t22iRWubTZcIO-l1EU2gGKuv1QAUUfUdlY83dEM; Secure,token_type=bearer

peristsCookies parameter not passed from methods to _httpRequest

All of the head, get, patch, delete, post, put methods do have a persistsCookies parameter but they do not get passed to _httpRequest

  static Future<dynamic> delete(String url, {headers, timeoutSeconds = DEFAULT_TIMEOUT_SECONDS, json = false, persistCookies = true}) {
    return _httpRequest(HTTP_METHOD_DELETE, url, headers: headers, timeoutSeconds: timeoutSeconds, json: json);
  }

Please upgrade shared_preferences version

Because app depends on requests ^1.0.2 which depends on shared_preferences ^0.4.3, shared_preferences ^0.4.3 is required. So, because app depends on shared_preferences ^0.5.1+1, version solving failed.

failed to install null safety version

i added the null safety in the yaml.
requests: ^4.0.0-nullsafety.0

but I got this error:
Because note depends on requests ^4.0.0-nullsafety.0 which doesn't match any versions, version solving failed.

Can't catch SocketException

Exception has occurred.
SocketException (SocketException: OS Error: Connection timed out, errno = 110, address = carlhung.mynetgear.com, port = 45396)

I can catch the returned result. but after a while, the simulator of android will crash with SocketException.
my code:

    try {
      request = await Requests.post(
        url + '/login',
        headers: {'content-type': 'application/json'},
        json: dic,
        verify: false,
        // timeoutSeconds: 5,
      );
    } catch (e) {
      return {"result":"Connection Error: $e"}; 
    }

Unable to catch TimeoutException when using flutter retry package

I'm wrapping my request to an api endpoint using the flutter retry package to retry the call if on socket exception or timeout exception. On timeout the Requests package throws a Timeout Exception that is not caught by the retry package and also in a try catch block it fails. Anyone have an idea why this is not working? Tried setting the timeout to about 20 seconds, same issue.

Future getPlayerElementSummary(int playerId) async {
try {
var playerElementSummaryUrl = baseUrl + '/element-summary/$playerId/';
var cookies =
await Requests.getStoredCookies(Requests.getHostname(loginUrl));
Requests.setStoredCookies(
Requests.getHostname(playerElementSummaryUrl), cookies);

  final response = await retry(
    () async {
      try {
        var data = await Requests.get(playerElementSummaryUrl,
            headers: head, timeoutSeconds: 20);
        return data.json();
      } catch (e) {
        print(e);
      }
    },
    retryIf: (e) => e is SocketException || e is TimeoutException,
  );
  return response;
} catch (e) {
  print(e);
}

}

Flutter doctor logs
` [โˆš] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.18362.900], locale en-US)

[โˆš] Android toolchain - develop for Android devices (Android SDK version 30.0.1)
[โˆš] Android Studio (version 4.0)
[โˆš] VS Code (version 1.50.0)
[โˆš] Connected device (1 available)

โ€ข No issues found!`

Cookie values incorrectly parsed

Describe the bug
Cookie values are not correctly parsed

To Reproduce
Steps to reproduce the behavior:
Hit any backend that provides a CSRF or XSRF token including data such as an expiry date

Expected behavior
The key is parsed correctly, but the value grabs the entire string, including "Set-Cookie"... it should only grab the string after the key name

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows11
  • Browser N/A
  • Version ^4.7.0

cookies not found within the same hostname

I have a problem regarding getting the cookies. I tried to get the cookies from the same hostname (but different endpoints) and it returns different result. One of the result returns the right tokens, the other not.

Steps to reproduce the behavior:

  1. Get the hostname of the diferent endpoints
  2. Get stored cookies using the hostname
  3. print the cookies

Expected behavior
The cookies shouldn't return null within the same hostname

Screenshots
image
image

  • OS: Windows 11

  • IDE: Android Studio Chipmunk 2021.2.1

  • Device: Huawei P30 Pro

  • OS: EMUI 12, Android 10

Additional context
I execute the api call within the workmanager, i did this before with Requests but it runs flawlessly

image

image

image

Fix body on request, convert to json only when needed

There's an assumption when doing a request and pass body into..

...
    if (body != null) {
      String contentTypeHeader;
      if (body is String) {
        bodyString = body;
        contentTypeHeader = "text/plain";
      } else if (body is Map || body is List) {
        bodyString = Common.toJson(body);

        if (bodyEncoding == RequestBodyEncoding.JSON) {
          contentTypeHeader = "application/json";
        } else if (bodyEncoding == RequestBodyEncoding.FormURLEncoded) {
          contentTypeHeader = "application/x-www-form-urlencoded";
        } else {
          throw Exception('unsupported bodyEncoding "$bodyEncoding"');
        }
      }

      if (contentTypeHeader != null && !Common.hasKeyIgnoreCase(headers, "content-type")) {
        headers["content-type"] = contentTypeHeader;
      }
    }
...

When the body is Map or List, always convert to json... but in some scenarios this is wrong, for instance, in a request like this:

POST /api/login HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Accept: */*

username=someusername&password=somepassword

Data needs to pass like key/value map, so only convert to json when you establish content type to "application/json", in any other case just pass raw body to the request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.