Skip to content

Instantly share code, notes, and snippets.

@jaysonss
Last active October 2, 2019 10:04
Show Gist options
  • Save jaysonss/53ea68bc380bcb95d78c291df7619f5c to your computer and use it in GitHub Desktop.
Save jaysonss/53ea68bc380bcb95d78c291df7619f5c to your computer and use it in GitHub Desktop.
自定义ImageProvider以支持https
class NetworkImageSSL extends ImageProvider<NetworkImageSSL> {
const NetworkImageSSL(this.url, {this.scale = 1.0, this.headers})
: assert(url != null),
assert(scale != null);
final String url;
final double scale;
final Map<String, String> headers;
@override
Future<NetworkImageSSL> obtainKey(ImageConfiguration configuration) {
return new SynchronousFuture<NetworkImageSSL>(this);
}
@override
ImageStreamCompleter load(NetworkImageSSL key) {
return new MultiFrameImageStreamCompleter(
codec: _loadAsync(key),
scale: key.scale,
informationCollector: () {
List<DiagnosticsNode> informationCollector;
informationCollector.add(DiagnosticsProperty('Image provider', this));
informationCollector.add(DiagnosticsProperty('Image key', key));
return informationCollector;
});
}
static final HttpClient _httpClient = new HttpClient()
..badCertificateCallback = ((X509Certificate cert, String host, int port) {
///add https certificate check
return true;
});
Future<ui.Codec> _loadAsync(NetworkImageSSL key) async {
assert(key == this);
final Uri resolved = Uri.base.resolve(key.url);
final HttpClientRequest request = await _httpClient.getUrl(resolved);
headers?.forEach((String name, String value) {
request.headers.add(name, value);
});
final HttpClientResponse response = await request.close();
if (response.statusCode != HttpStatus.ok) {
throw new Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');
}
final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
if (bytes.lengthInBytes == 0) {
throw new Exception('NetworkImageSSL is an empty file: $resolved');
}
return await ui.instantiateImageCodec(bytes);
}
@override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
final NetworkImageSSL typedOther = other;
return url == typedOther.url && scale == typedOther.scale;
}
@override
int get hashCode => hashValues(url, scale);
@override
String toString() => '$runtimeType("$url", scale: $scale)';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment