OkGo的教程网上挺多的,这里我着重展现上传下载图片
环境:Android studio 3.3.2 后端springboot
一、导入依赖
implementation 'com.lzy.net:okgo:+'
二、封装一下OkGo(我封装的可能不是专业的,不要吐槽我,你可以参考下别人的封装)
定义一个接口
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
public interface Api {
/**
* 保存头像到服务器
* headFile 头像文件
* user你的其它参数
* stringCallback 回调
*/
public void saveHeadImgToServer(File headFile, User user, StringCallback stringCallback);
/**
* 下载头像到服务器
*/
public void getHeadImgToServer(String phone, FileCallback fileCallback);
}
定义一个类存放地址,你也可以直接写到ApiService
public class ApiPath {
/**
* ip地址
*/
public static final String BASE="http://192.168.53.81:8080"; //地址不存在,换成你自己的,最好不写localhost
/**
* 上传头像地址
*/
public static final String saveHeadImg=BASE+"/user/headIcon";
/**
* 下载头像地址
*/
public static final String downloadHeadImg=BASE+"/user/downloadHeadIcon";
}
实现接口
public class ApiService implements Api{
@Override
public void saveHeadImgToServer(File headFile, User user, StringCallback stringCallback) {
OkGo.post(ApiPath.saveHeadImg)
.tag(this)
.params("icon", headFile)
.params("userPhone",user.getUserPhone())
.params("userNickname",user.getUserNickname())
.execute(stringCallback);
}
@Override
public void getHeadImgToServer(String phone, FileCallback fileCallback) {
OkGo.get(ApiPath.downloadHeadImg)
.tag(this)
.params("phone", phone)
.execute(fileCallback);
}
}
在需要的地方调用方法
//上传图片
ApiService apiService=new ApiService();
apiService.saveHeadImgToServer(getFile(head,phoneNum),newU, new StringCallback() {
@Override
public void onSuccess(Response response) {
String status=response.body().toString();
if(status.equals("1")){
saveBitmapToSDK(head);
Log.i("TAG","success");
}else{
Toast.makeText(AddUserInfoActivity.this, "信息保存失败!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Response response) {
super.onError(response);
Toast.makeText(AddUserInfoActivity.this, "请求服务器失败!", Toast.LENGTH_SHORT).show();
}
});
//--------------------其它辅助方法---------------------------
/**
*将bitmap转为File
*phone 是我给图片命名用的,你不需要可以不加,用时间命名也行
*/
public File getFile(Bitmap bitmap,String phone) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
System.out.println(Environment.getExternalStorageDirectory());
headImgName=phone+"_"+System.currentTimeMillis()+".jpg";
File file = new File(Environment.getExternalStorageDirectory() + "/"+headImgName);
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
int x = 0;
byte[] b = new byte[1024 * 100];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
/**
*将bitmap存入SDK
*bitmap 要保存的图片
*/
private void saveBitmapToSDK(Bitmap img){
String headImgName="test.jpg"
if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)){// 判断是否可以对SDcard进行操作
// 获取SDCard指定目录下
String sdCardDir = Environment.getExternalStorageDirectory()+ "/mimages/headImg/";
File dirFile = new File(sdCardDir); //目录转化成文件夹
if (!dirFile .exists()) { //如果不存在,那就建立这个文件夹
dirFile .mkdirs();
} //文件夹有啦,就可以保存图片啦
File file = new File(sdCardDir, headImgName);// 在SDcard的目录下创建图片文
FileOutputStream out=null;
try {
out = new FileOutputStream(file);
img.compress(Bitmap.CompressFormat.JPEG, 100, out); //压缩图片,100为不压缩
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
保存图片的后端接口
//你在实际使用时请将user换成你自己的参数,或者不传。返回参数类型也根据你自己需要设置,只要注意后端参数和Android端参数对应问题
//保存图片
@RequestMapping(value = "/headIcon")
public int saveHeadIcon(@RequestParam MultipartFile icon, User user, HttpSession session)
throws IllegalStateException, IOException {
if (icon.getSize() > 0 && "" != user.getUserPhone()) {
// 文件保存路径
String path = session.getServletContext().getRealPath("/images/");
File fileDir = new File(path);
if (!fileDir.exists() || !fileDir.isDirectory()) {
fileDir.mkdirs();
}
String fileName = icon.getOriginalFilename();
File file = new File(path, fileName);
// 转存文件
icon.transferTo(file);
// ------将图片路径存入数据库------
return this.userService.updateHeadImgAndNickNameByPhone(path+fileName, user);
}
return 0;
}
//下载图片----参数phone换成你自己的参数。返回类型String也可换成你自己喜欢的,我这里是为了判断是否保存成功
@RequestMapping("/downloadHeadIcon")
public String downloadHeadIcon(HttpServletResponse response,String phone) {
String path=this.userService.getUserHeadImg(phone);
if(""==path) return "-1";
File file = new File(path);
if (!file.exists()) {
return "-1";
}
response.reset();
response.setHeader("Content-Disposition", "attachment;fileName=" + path);
try {
InputStream inStream = new FileInputStream(path);
OutputStream os = response.getOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = inStream.read(buff)) > 0) {
os.write(buff, 0, len);
}
os.flush();
os.close();
inStream.close();
} catch (Exception e) {
e.printStackTrace();
return "-2";
}
return "0";
}
前端下载图片
apiService.getHeadImgToServer(phone, new FileCallback() {
@Override
public void onSuccess(Response response) {
File file=new File(response.body().toString());
Bitmap bit=BitmapFactory.decodeFile(file.getAbsolutePath());
if(null!=bit){
iv_mine_avatar.setImageBitmap(bit);
}
}
@Override
public void onError(Response response) {
super.onError(response);
Toast.makeText(getActivity(), "请求服务器失败!", Toast.LENGTH_SHORT).show();
}
});
User文件(供参考)
public class User {
private String userPhone;
private String userName;
private String userNickname;
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone == null ? null : userPhone.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname == null ? null : userNickname.trim();
}
}
从sdk取出图片
private Bitmap getBitmapFromSDK(String path){
File mFile=new File(path);
//若该文件存在
if (mFile.exists()) {
return BitmapFactory.decodeFile(path);
}else{
return null;
}
}
注意事项:若服务器在本地localhost8080端口。Android 端要和手机在同一网段才能真机调试。并且注意有时候防火墙也会阻断通信,不成功时可以试下关闭防火墙。以及检查参数是否对应