Wiki_Flutter_Network - inoueshinichi/Wiki_Flutter GitHub Wiki

Dart/Flutterによるネットワークアクセス方法

参考

HttpClientRequest

  • HttpClientクラスを用いる
import 'dart.io';

HttpClientRequest httpCliReq = await HttpClient();

// Httpアクセスは, *.get()を使う
httpCliReq.get('host', port, 'URL/path');

// Httpsアクセスは, *.getUrl()を使う
final Uri uri = Uri.parse('your_uri');
httpCliReq.getUrl(uri);

httpCliReq.close();

HttpClientResponse

  • HttpClientResponseクラスからUTF-8形式のコンテンツを得る
  • サーバーから送られてきたコンテンツを取り出す際は, エンコーディングを揃えるが実質UTF-8
  • Stream<String> <HttpClientResponse>.transform(utf8.decoder).join()
  • UTF-8からUTF-16
import 'dart:convert';
import 'dart:io';

void getData() async {
  var http = await HttpClient();
  HttpClientRequest httpCliReq = await http.get(`home.tiny-tank.jp`, 80, '/your/url/path');
  HttpClientResponse httpCliRes = await httpCliReq.close();
  final Stream<String> stream = await httpCliRes.transform(utf8.decoder).join();

}

application/json; charset=utf-8によるHTTP通信

  • HttpClient
  • HttpClientRequest
  • HttpClientResponse
  • POST(HTTP): *.post(ホスト, ポート番号, パス)
  • POST(HTTPS): *.postUrl(Uri)
  • GET(HTTP): *.get(ホスト, ポート番号, パス)
  • GET(HTTPS): *.getUrl(Uri)
  • .headers.set(, 値)
  • httpCliReq.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
  • body部へのコンテンツ埋め込み: httpCliReq.write(/*コンテンツ*/基本Jsonフォーマット)
class Album {
  final int id;
  final String title;
  final int userId;
  
  Album({
    required this.id,
    required this.title,
    required this.userId
  });
  
  // factory
  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(id: json['id'] as int,
                 title: json['title'] as String,
                 userId: json['userId'] as int);
  }
}

// POST with HTTPS
void postJsonDataWithHttps() async {
  final transferObj = {
    "title": "foo",
    "author": "tiny-tank",
    "content": "My handle name is `tiny-tank`.",
  };
  
  // Request
  final String jsonData = json.encode(transferObj);
  var https = await HttpClient();
  final Uri postUri = Uri.parse("https://jsonplaceholder.typicode.com/posts");
  HttpClientRequest httpCliReq = await https.postUrl(postUri);
  httpCliReq.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=utf8");
  httpCliReq.write(jsonData);

  // Response
  HttpClientResponse httpCliRes = await httpCliReq.close();
  final String value = await httpCliRes.transfer(utf8.decoder).join();

  ...
}
⚠️ **GitHub.com Fallback** ⚠️