Android okhttp的使用
首先在build.gradle中引入okhttp
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.squareup.okio:okio:1.17.4'
下面是demo(用okthttp下载网络上的资源)文章来源:https://www.toymoban.com/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将资源上传至网络文章来源地址https://www.toymoban.com/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))
// 提交文件,第一个参数是键(key="第一个参数"),第二个参数是文件名,第三个是一个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("文件上传出现问题");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
LogUtils.i("log文件上传成功");
}
});
到了这里,关于Android OKhttp使用(下载和上传文件)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!