Android okhttp的使用
首先在build.gradle中引入okhttp
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.squareup.okio:okio:1.17.4'
下面是demo(用okthttp下載網(wǎng)絡(luò)上的資源)文章來源:http://www.zghlxwxcb.cn/news/detail-505535.html
//下載路徑,如果路徑無效了,可換成你的下載路徑
final String url = "http://sancloud.com/resource/" + file;
Request request = new Request.Builder().url(url).build();
new OkHttpClient().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下載失敗
e.printStackTrace();
Log.i("DOWNLOAD","download failed");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Sink sink = null;
BufferedSink bufferedSink = null;
String filename = url.substring(url.lastIndexOf("/") + 1);
//這是里的mContext是我提前獲取了android的context
File localFile = mContext.getFilesDir()+File.separator+filename
try {
sink = Okio.sink(localFile);
bufferedSink = Okio.buffer(sink);
bufferedSink.writeAll(response.body().source());
bufferedSink.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedSink != null) {
bufferedSink.close();
}
}
}
});
用okthttp將資源上傳至網(wǎng)絡(luò)文章來源地址http://www.zghlxwxcb.cn/news/detail-505535.html
// 獲得輸入框中的路徑
File file = new File(path);
OkHttpClient client = new OkHttpClient();
// 上傳文件使用MultipartBody.Builder
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
// 提交普通字段
.addFormDataPart("id", String.valueOf(id))
// 提交文件,第一個參數(shù)是鍵(key="第一個參數(shù)"),第二個參數(shù)是文件名,第三個是一個RequestBody
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file))
.build();
// POST請求
Request request = new Request.Builder()
.url("http://sancloud.com:9111/MobileCenter/upload")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogUtils.w("文件上傳出現(xiàn)問題");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
LogUtils.i("log文件上傳成功");
}
});
到了這里,關(guān)于Android OKhttp使用(下載和上傳文件)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!