问题1 java.net.UnknownServiceException: CLEARTEXT communication to * not permitted by network
在Android O 升 P (8.0升9.0)的时候,会报以下异常
java.net.UnknownServiceException: CLEARTEXT communication to * not permitted by network
因为 Android P 是默认禁止访问http的API的。
解决办法:
1,使用https
2,暂时先绕过HTTP限制
在res文件夹下创建xml目录,新建network_security_config.xml文件,名字随意
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
在AndroidManifest.xml的Application中添加配置引用
<application
..
android:networkSecurityConfig="@xml/network_security_config"
... >
//data 建议图片进行文件压缩上传
//token请求java后台一下获得七牛云token
//imgKey自行定义的图片每张图片不固定格式名
private fun upLoadData(data: ByteArray, token: String, imgKey: String, success: ((key: String) -> Unit), options: UploadOptions? = null) { Observable.create<String> { emitter -> QiNiuUtil.put(data, imgKey, token, UpCompletionHandler { key, info, _ -> if (info.isOK) { emitter.onNext(key) Log.d("xg", "上传图片成功") } else { Log.d("xg", "info上传图片失败${info}") } }, options) }.compose(RxTransformer.io2Main()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ key -> success.invoke(key) }, { upLoadData(data, token, imgKey, success, options) } ) }
private fun saveBitmapToFile(file: File): ByteArray? { try { // BitmapFactory options to downsize the image val o = BitmapFactory.Options() o.inJustDecodeBounds = true o.inSampleSize = 6 // factor of downsizing the image var inputStream = FileInputStream(file) //Bitmap selectedBitmap = null; BitmapFactory.decodeStream(inputStream, null, o) inputStream.close() // The new size we want to scale to val REQUIRED_SIZE = 75 // Find the correct scale value. It should be the power of 2. var scale = 1 while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) { scale *= 2 } val o2 = BitmapFactory.Options() o2.inSampleSize = scale inputStream = FileInputStream(file) val selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2) inputStream.close() return compressAndGenImage(selectedBitmap!!, 50) } catch (e: Exception) { return null } } /** * 压缩图片 返回字节流不保存 * * @param image * @param maxSize target will be compressed to be smaller than this size.(kb) * @throws IOException */ @SuppressLint("WrongThread") @Throws(IOException::class) private fun compressAndGenImage(image: Bitmap, maxSize: Int): ByteArray { val os = ByteArrayOutputStream() var options = 100//从不压缩开始,因为有图片可能不到压缩条件 image.compress(Bitmap.CompressFormat.JPEG, options, os) //超过MaxKb的话再压缩 while (os.toByteArray().size / 1024 > maxSize) { os.reset()//重新压缩 options -= 10//比例加10 image.compress(Bitmap.CompressFormat.JPEG, options, os) } return os.toByteArray() }
这是flutter中插件使用七牛云Android版部分代码 有疑问请留言