首先在build.gradle中引入okhttp
implementation 'com.squareup.okhttp3:okhttp:3.14.2' implementation 'com.squareup.okio:okio:1.17.4'
下面是demo(用okthttp下载网络上的资源)
//下载路径,如果路径无效了,可换成你的下载路径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将资源上传至网络
// 获得输入框中的路径 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文件上传成功"); } });
来源地址:https://blog.csdn.net/weixin_49855330/article/details/129379974