FlutterでのHTTPリクエスト 質問する

FlutterでのHTTPリクエスト 質問する

私は Android 用の Retrofit を使用しています。REST ベースの Web サービスを介して JSON を取得およびアップロードするのは簡単です。Flutter の Web サービス用の Retrofit と同等のライブラリを入手できますか?

ベストアンサー1

アップデート

もともと私はここで最初に答えを書きましたが、後でより詳細な投稿を書くことになりました。

完全なソースコードもそこにあります。

FlutterでHTTPリクエストを送信する方法

この回答では、HTTPリクエストの送信方法を説明します。http パッケージDartチームによるものです。より高度な機能が必要な場合は、Dio パッケージコメントに記載されています。

使用するのはJSONプレースホルダー以下の API の例のターゲットとして。

GET     /posts
GET     /posts/1
GET     /posts/1/comments
GET     /comments?postId=1
GET     /posts?userId=1
POST    /posts
PUT     /posts/1
PATCH   /posts/1
DELETE  /posts/1

設定

httpパッケージの依存関係を追加しますpubspec.yaml

dependencies:
  http: ^0.12.0+1

GETリクエスト

_makeGetRequest() async {

  // make request
  final response = await get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  
  // sample info available in response
  final statusCode = response.statusCode;
  final headers = response.headers;
  final contentType = headers['content-type'];
  final json = response.body;

  // TODO convert json to object...

}

を上記の他のGETリクエスト/postsに置き換えます。を使用するとJSONオブジェクトの配列が返されますが、を使用すると単一のJSONオブジェクトが返されます。/posts/1posts/posts/1ダーツ:変換生の JSON 文字列をオブジェクトに変換します。

POSTリクエスト

_makePostRequest() async {
  
  // set up POST request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello", "body": "body text", "userId": 1}';

  // make POST request
  final response = await post(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;
  
  // this API passes back the id of the new item added to the body
  final body = response.body;
  // {
  //   "title": "Hello",
  //   "body": "body text",
  //   "userId": 1,
  //   "id": 101
  // }

}

PUTリクエスト

PUT リクエストは、リソースを置き換えるか、存在しない場合は作成することを目的としています。

_makePutRequest() async {

  // set up PUT request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello", "body": "body text", "userId": 1}';

  // make PUT request
  final response = await put(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;

  // this API passes back the updated item with the id added
  final body = response.body;
  // {
  //   "title": "Hello",
  //   "body": "body text",
  //   "userId": 1,
  //   "id": 1
  // }

}

PATCHリクエスト

PATCH リクエストは、既存のリソースを変更することを目的としています。

_makePatchRequest() async {

  // set up PATCH request arguments
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  final headers = {"Content-type": "application/json"};
  final json = '{"title": "Hello"}';

  // make PATCH request
  final response = await patch(url, headers: headers, body: json);

  // check the status code for the result
  final statusCode = response.statusCode;

  // only the title is updated
  final body = response.body;
  // {
  //   "userId": 1,
  //   "id": 1
  //   "title": "Hello",
  //   "body": "quia et suscipit\nsuscipit recusandae... (old body text not changed)",
  // }

}

渡される JSON 文字列にはタイトルのみが含まれており、PUT の例のような他の部分は含まれていないことに注意してください。

削除リクエスト

_makeDeleteRequest() async {

  // post 1
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');

  // make DELETE request
  final response = await delete(url);

  // check the status code for the result
  final statusCode = response.statusCode;

}

認証

上記で使用したデモサイトでは必要ありませんでしたが、認証ヘッダーを含める必要がある場合は、次のようにします。

基本認証

// import 'dart:convert'

final username = 'username';
final password = 'password';
final credentials = '$username:$password';
final stringToBase64Url = utf8.fuse(base64Url);
final encodedCredentials = stringToBase64Url.encode(credentials);

final headers = {
  HttpHeaders.contentTypeHeader: "application/json", // or whatever
  HttpHeaders.authorizationHeader: "Basic $encodedCredentials",
};

ベアラー(トークン)認証

// import 'dart:io';

final token = 'WIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv';

final headers = {
  HttpHeaders.contentTypeHeader: "application/json", // or whatever
  HttpHeaders.authorizationHeader: "Bearer $token",
};

関連している

おすすめ記事