黑马程序员技术交流社区
标题:
【上海校区】okHttp上传图片\下载图片
[打印本页]
作者:
梦缠绕的时候
时间:
2018-11-28 09:35
标题:
【上海校区】okHttp上传图片\下载图片
首先我们需要先导入依赖,或者去看GitHub的官方文档找最新版:
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
1
其次我们就需要加入权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
1
2
3
一、布局很简单,就2个按钮加一个图片
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/downLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载图片"/>
<Button
android:id="@+id/upLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上传图片"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="55dp"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
二、MainActivity代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mImageView;
private String downLoadUrl = "https://10.url.cn/eth/ajNVdqHZLLAxibwnrOxXSzIxA76ichutwMCcOpA45xjiapneMZsib7eY4wUxF6XDmL2FmZEVYsf86iaw/";
private String upLoadUrl = "https://www.718shop.com/sell/sell.m.picture.upload.do";
//handler成功和失败的标识
private static final int SUCCESS = 0;
private static final int FAILURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case SUCCESS:
//拿到obj中的数据
byte[] bytes = (byte[]) msg.obj;
//使用BitmapFactory将字节转换成bitmap类型
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//设置图片
mImageView.setImageBitmap(bitmap);
break;
case FAILURE:
Toast.makeText(MainActivity.this, "请求数据失败", Toast.LENGTH_SHORT).show();
break;
}
}
};
private void initView() {
Button downLoad = findViewById(R.id.downLoad);
Button upLoad = findViewById(R.id.upLoad);
mImageView = findViewById(R.id.imageView);
downLoad.setOnClickListener(this);
upLoad.setOnClickListener(this);
}
//点击
@Override
public void onClick(View v) {
switch (v.getId()){
//下载
case R.id.downLoad:
downLoad();
break;
//上传
case R.id.upLoad:
upLoad();
break;
}
}
//下载
private void downLoad() {
//创建okHttp
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(8, TimeUnit.SECONDS)
.readTimeout(8, TimeUnit.SECONDS)
.build();
//创建request
Request request = new Request.Builder()
.url(downLoadUrl).build();
//创建call
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.sendEmptyMessage(FAILURE);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//将流转换成字节
byte[] bytes = response.body().bytes();
//获取message对象
Message message = mHandler.obtainMessage();
//将字节存入obj
message.obj = bytes ;
//设置一个标识
message.what = SUCCESS;
//发送
mHandler.sendMessage(message);
}
});
}
//这里需要注意下我们图片的路径:
/* 文件存储:应用程序可以把数据存储在外存储卡(sd卡),存放的路径:/mnt/sdcard/文件名,可以放较的大数据
注意:Android系统版本4.3之前路径是/mnt/sdcard ,Android系统版本4.3之后storage/sdcard*/
//上传
private void upLoad() {
//创建文件对象
File file = new File(Environment.getExternalStorageDirectory() + "/Download" , "timg.jpg");
//创建RequestBody封装参数
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//创建MultiparBody,给RequestBody进行设置
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", "timg.jpg", fileBody)
.build();
//创建Request
Request request = new Request.Builder()
.url(upLoadUrl)
.post(multipartBody)
.build();
//创建okHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(8, TimeUnit.SECONDS)
.connectTimeout(8, TimeUnit.SECONDS)
.writeTimeout(8,TimeUnit.SECONDS)
.build();
//创建call对象
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("wjh","upLoad 、 e=" + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("wjh","upLoad 、 response = "+response.body().string());
}
});
}
}
---------------------
作者:家辉,喂
来源:CSDN
原文:
https://blog.csdn.net/jiahui6666/article/details/84035024
版权声明:本文为博主原创文章,转载请附上博文链接!
作者:
不二晨
时间:
2018-11-28 15:54
奈斯
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2