布局文件
<Button
android:id="@+id/Donw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
/>
<Button
android:id="@+id/Up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上传"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
实现下载模块
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder().get().url(UrlPath).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handler.sendEmptyMessage(FAILURE);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
byte[] read = response.body().bytes();
Message message = handler.obtainMessage();
message.obj = read;
message.what = RESPONSE;
handler.sendMessage(message);
}
});
实现上传模块
//上传的接口
String url = "https://www.718shop.com/sell/sell.m.picture.upload.do";
//创建上传文件
File file = new File(Environment.getExternalStorageDirectory()+"/Download/", "jjj.jpg");
//创建ReaquestBody封装参数
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
//创建MultipartBody给requestBody进行设置
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image","jjj.jpg",requestBody)
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();
OkHttpClient Client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build();
Call call = Client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("lsq","上传失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("lsq","上传成功"+response.body().string());
}
});
本文详细介绍了如何使用OkHttp库在Android应用程序中实现图片的上传和下载功能,包括设置请求头、处理响应以及进度回调等关键步骤。


被折叠的 条评论
为什么被折叠?



