美文网首页
Retrofit图文上传黑科技

Retrofit图文上传黑科技

作者: 夜溪风 | 来源:发表于2017-09-04 11:17 被阅读0次

一.背景

    在一次做项目的时候我们采用了Rxjava和Retrofit来进行网络请求,开始特别顺利,但是到了一个要上传图片和文字的时候和后台对接总是不成功,在不断的探索中我们最终找到了完美的解决方案,在此和各位读者交流一下,欢迎大神们指导。

二.原因

图片上传的时候图片会解析成字符串,这样导致图片这个参数过长,后台接口参数长度限制在256,所以直接使用post上传的时候后台不能够识别,这个时候我们应该把我们的参数变成一个body。

三.使用

1.在接口文件添加要调用那个接口

v1图

*注意事项:

a:这里报红的地方添加自己说需要的解析文件

b.post内可以使用绝对路径,同样可以使用相对路径,个人建议使用相对路径,这样的话修改的时候方便。

2.body的构建

v2图

*注意事项:

compressUrl为转换过的文件路径,具体获取如下:


//1.filePath拍照所得的文件路径2.targetPath转换之后的路径,3.quality 压缩的质量

public staticStringcompressImage(String filePath,String targetPath, int quality) {

Bitmap bm =getSmallBitmap(filePath);//获取一定尺寸的图片

intdegree =readPictureDegree(filePath);//获取相片拍摄角度

if(degree !=0) {//旋转照片角度,防止头像横着显示

bm =rotateBitmap(bm,degree);

}

File outputFile =newFile(targetPath);

try{

if(!outputFile.exists()) {

outputFile.getParentFile().mkdirs();

//outputFile.createNewFile();

}else{

outputFile.delete();

}

FileOutputStream out =newFileOutputStream(outputFile);

bm.compress(Bitmap.CompressFormat.JPEG,quality,out);

}catch(Exception e) {

}

return outputFile.getPath();

}

/**

* 根据路径获得图片信息并按比例压缩,返回bitmap

*/

public staticBitmapgetSmallBitmap(String filePath) {

finalBitmapFactory.Options options =newBitmapFactory.Options();

options.inJustDecodeBounds=true;//只解析图片边沿,获取宽高

BitmapFactory.decodeFile(filePath,options);

// 计算缩放比

options.inSampleSize=calculateInSampleSize(options,480,800);

// 完整解析图片返回bitmap

options.inJustDecodeBounds=false;

returnBitmapFactory.decodeFile(filePath,options);

}

3.使用retrofit调用接口

v3图

commonsubscriber是我们自己封装之后的subscriber ,大佬可以使用自己的subscribe,并做后续处理。

相关文章

网友评论

      本文标题:Retrofit图文上传黑科技

      本文链接:https://www.haomeiwen.com/subject/wvacxxtx.html