Search code examples
httpfluttercertificatehttpresponsepem

Add Certificate in Flutter


I want to get a Http-response from the Website 'https://www.phwt.de'. I tried to add the certificate in Flutter, but it doesn't work. The pem-file was added into the directory 'assets/Certificates' and it was added in pubspec.yaml. The error is, that the file cannot be opened.

Future initiate() async {
  SecurityContext clientContext = new SecurityContext()
    ..setTrustedCertificates('assets/Certificates/personal.pem');
  var client = new HttpClient(context: clientContext);
  var request = await client.getUrl(Uri.parse("https://www.phwt.de"));
  var response = await request.close();

  return response;
}

Error: OS Error: No such file or directory, errno = 2


Solution

  • You can pass it as binary data:

      ByteData bytes = await rootBundle.load('assets/Certificates/personal.pem');
      SecurityContext clientContext = new SecurityContext()
        ..setTrustedCertificatesBytes(bytes.buffer.asUint8List());