Skip to content

Commit

Permalink
updated readme, added bytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
jossef committed Oct 20, 2019
1 parent 88453d5 commit f240fd0
Show file tree
Hide file tree
Showing 7 changed files with 7,680 additions and 20 deletions.
105 changes: 90 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# flutter http json with cookies
![banner-01](https://user-images.githubusercontent.com/1287098/67152735-969fd300-f2e5-11e9-9aa5-b73652ac502e.png)

a flutter library that helps with http requests and stored cookies (inspired by python's [requests](https://github.com/psf/requests) module).
# Flutter HTTP client + json + cookies.

server side cookies (via response header `SET-COOKIE`) are stored using the assistance of `shared_preferences`. Stored cookies will be send seamlessly on the next http requests you make to the same domain (simple implementation, similar to a web browser)
a flutter library to simply call HTTP requests (inspired by python [requests](https://github.com/psf/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 `shared_preferences`. 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
Expand All @@ -15,34 +18,106 @@ dependencies:
```
## Usage
Start by importing the library
```dart
import 'package:requests/requests.dart';
```

in your Dart code, you can use:
Let's make a simple HTTP request

```dart
import 'package:requests/requests.dart';
var r = await Requests.get("https://google.com");
r.raiseForStatus();
String body = r.content();
```


HTTP get, body as plain text
### the `Response` object
just like in python's request module, the `Response` object has this functionallity

- `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.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 respone as a list of bytes
- `r.content()` - return the body in the respone as a string
- `r.json()` - recodes the body in the respone 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

> 💡 Only one optional argument can be used in a single request `body` or `json`

### Class Methods

- `.getHostnam(url)` - returns the hostname of the given url
- `.clearStoredCookies(hostname)` - clears the stored cookies for the hostname
- `.setStoredCookies(hostname, Map<String, String>)` - set the stored cookies for the hostname
- `.getStoredCookies(hostname)` - returns a Map<String, String> of the stored cookies for the hostname


## Examples

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

```dart
String body = await Requests.get("https://mydomain.com");
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 get, body as parsed json
---

HTTP delete

```dart
dynamic body = await Requests.get("https://mydomain.com/api/v1/foo", json: true);
var r = await Requests.delete("https://reqres.in/api/users/10");
r.raiseForStatus();
```

HTTP post, body is map or a list (being sent as application/x-www-form-urlencoded, until stated otherwise in `bodyEncoding` parameter), result is json
---

Ignore SSL self-signed certificate

```dart
dynamic body = await Requests.post("https://mydomain.com/api/v1/foo", json: true, body: {"foo":"bar"} );
```
var r = await Requests.get('https://expired.badssl.com/', verify: false);
r.raiseForStatus();
```

HTTP delete
---

Play with stored cookies

```dart
await Requests.delete("https://mydomain.com/api/v1/foo/123");
```
String url = "https://reqres.in/api/users/10";
String hostname = Requests.getHostname(url);
await Requests.clearStoredCookies(hostname);
await Requests.setStoredCookies(hostname, {'session': 'bla'});
var cookies = await Requests.getStoredCookies(hostname);
expect(cookies.keys.length, 1);
await Requests.clearStoredCookies(hostname);
cookies = await Requests.getStoredCookies(hostname);
expect(cookies.keys.length, 0);
```

<a href="https://www.freepik.com/free-photos-vectors/business">Business vector created by freepik - www.freepik.com</a>
10 changes: 7 additions & 3 deletions lib/src/requests.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@ class Response {
throwForStatus();
}

List<int> bytes() {
return _rawResponse.bodyBytes;
}

String content() {
return utf8.decode(_rawResponse.bodyBytes, allowMalformed: true);
return utf8.decode(bytes(), allowMalformed: true);
}

dynamic json() {
Expand Down Expand Up @@ -120,7 +124,7 @@ class Requests {

static String getHostname(String url) {
var uri = Uri.parse(url);
return uri.host;
return "${uri.host}:${uri.port}";
}

static Future<Response> _handleHttpResponse(String hostname, http.Response rawResponse, bool persistCookies) async {
Expand Down Expand Up @@ -277,7 +281,7 @@ class Requests {
throw ArgumentError("invalid url, must start with 'http://' or 'https://' sheme (e.g. 'http://example.com')");
}

String hostname = "${uri.host}:${uri.port}";
String hostname = getHostname(url);
headers = await _constructRequestHeaders(hostname, headers);
String bodyString = "";

Expand Down
Binary file added logo/banner-01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5,482 changes: 5,482 additions & 0 deletions logo/banner.ai

Large diffs are not rendered by default.

Binary file added logo/social-01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit f240fd0

Please sign in to comment.