如何使用okhttp在android中创建数据流并写入设备



我正在做的事情:我使用连接从服务器下载文件并写入存储

发生了什么:代码正在中工作

我正在尝试做的事情:如何使用okhttp 实现同样的效果

try {
val url = URL(DICTIONARY_FILE_URL)
val conection = url.openConnection()
conection.connect()
// getting file length
// input stream to read file - with 8k buffer
val input = BufferedInputStream(url.openStream(), 8192)
// Output stream to write file
val directoryPathName = Environment.getExternalStorageDirectory().absolutePath.plus("/CNX/dictionary/")
val dictionaryFileName = "DictionaryEN.quickdic"
var f =  File(directoryPathName)
if(!f.isDirectory) {
f.mkdirs()
}
val output = FileOutputStream(directoryPathName.plus(dictionaryFileName))
val data = ByteArray(1024)
var count: Int? = 0
while ({ count = input.read(data);count }() != -1) {
output.write(data, 0, count!!)
}
// flushing output
output.flush()
// closing streams
output.close()
input.close()
isJobSuccess = true
//sharedPreferences[IS_DICTIONARY_DOWNLOADED] = true
} catch (e: Exception) {
Log.e("Exception",e.message)
isJobSuccess = false
//sharedPreferences[IS_DICTIONARY_DOWNLOADED] = false
}
  1. 使用OkHttp异步下载文件的示例

    fun downloadFileAsync(downloadUrl: String) {
    val client = OkHttpClient();
    val request = Request.Builder().url(downloadUrl).build();
    client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
    Log.e("fail", e.printStackTrace().toString())
    }
    override fun onResponse(call: Call, response: Response) {
    if (!response.isSuccessful) {
    Log.e("fail", "Download error")
    }else{
    // Output stream to write file
    val directoryPathName = Environment.getExternalStorageDirectory().absolutePath.plus("/CNX/dictionary/")
    val dictionaryFileName = "DictionaryEN.quickdic"
    val f =  File(directoryPathName)
    if(!f.isDirectory) {
    f.mkdirs()
    }
    val output = FileOutputStream(directoryPathName.plus(dictionaryFileName))
    response.body?.let {
    output.write(it.bytes())
    }
    // flushing output
    output.flush()
    // closing streams
    output.close()
    }
    }
    })
    }
    
  2. 使用OkHttp同步下载文件的示例

    fun downloadFileSync(downloadUrl: String) {
    val client = OkHttpClient();
    val request = Request.Builder().url(downloadUrl).build();
    val response = client.newCall (request).execute();
    if (!response.isSuccessful) {
    Log.e("fail", "Failed to download file: " + response)
    }else {
    val directoryPathName = Environment.getExternalStorageDirectory().absolutePath.plus("/CNX/dictionary/")
    val dictionaryFileName = "DictionaryEN.quickdic"
    val f = File(directoryPathName)
    if (!f.isDirectory) {
    f.mkdirs()
    }
    val output = FileOutputStream(directoryPathName.plus(dictionaryFileName))
    response.body?.let {
    output.write(it.bytes())
    }
    // flushing output
    output.flush()
    // closing streams
    output.close()
    }
    }
    

build.gradle

implementation("com.squareup.okhttp3:okhttp:4.5.0")

最新更新