Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - Flutter https with self signed certificate

I am using flutter to connect with java java server implementation over https. I first tested it to be working using just http.

I then switched to https on the server side and pointed it at my self signed certificate I created using keytool.

Then I tried to connect to it using the http dart package. The resulted in the following exception...

Unhandled Exception: HandshakeException: Handshake error in client (OS Error: E/flutter ( 7370): CERTIFICATE_VERIFY_FAILED: self signed certificate(handshake.cc:354))

I am assuming I need to set my client to trust my servers self signed certificate. I have looked at the APi reference and could not figure out how to get this to happen...

My dart code in my flutter app is as follows...

void testMessage() {
    var url = 'https://192.168.100.105:8443';
    var response = await http.post(url, body: "{"message_name": "TestMessage", "contents": { "field1":"blah", "field2":"blah" }}");
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While Pascal's answer works, it only applies to the dart:io HttpClient. To apply the badCertificateCallback to the http package's Client instances, do the following:

Create a class that overrides HttpOverrides in the following way:

class DevHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext context) {
    return super.createHttpClient(context)
      ..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  }
}

Then in your main, instantiate your class as the global HttpOverride:

HttpOverrides.global = new DevHttpOverrides();

This should make all Client ignore bad certificates and is therefore onl;y recommended in development. Credit goes to this issue: https://github.com/dart-lang/http/issues/458


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...