我想使用Retrofit重写上传文件到服务器。
身体的服务器api请求是
{“file_name”: “my_pic”, “content_base64”: “MKMD….”}
在上传之前还需要压缩图像并对内容进行编码。我们目前的实施是:
Bitmap bmp = BitmapFactory.decodeFile(localPath);
ByteArrayOutputStream outputStream= new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
byte[] byteArrayImage = outputStream.toByteArray();
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
JSONObject jObject = new JSONObject();
try {
jObject.put("file_name", "test.jpg");
jObject.put("content_base64", encodedImage);
String jObjectString = jObject.toString();
URL url = new URL(serverPath);
...
connection.setRequestMethod("PUT");
connection.setUseCaches(false);
OutputStreamWriter wr = new
OutputStreamWriter(connection.getOutputStream());
wr.write(jObjectString);
wr.close();
...
}
我想将上面的代码更改为Retrofit upload。在研究了使用OkHttp的RequestBody或MultipartBody.Part类的Retrofit Upload Example之后。但我不知道如何转换上面的代码。
有什么建议吗?
1.创建与请求和添加方法的接口
public interface PostRequests {
@PUT("your_url")
Call<YourResponse> upload(@Body YourRequest yourRequest);
}
2.为请求体创建pojo
public class YourRequest {
@SerializedName("file_name")
@Expose
private String fileName;
@SerializedName("content_base64")
@Expose
private String picture;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
3.Init
public class Api {
private PostRequests mPostRequests;
public Api() {
mPostRequests = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("your_base_url")
.build()
.create(PostRequests.class);
}
public Call<YourResponse> upload(String localPath) {
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeFile(localPath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
byte[] byteArrayImage = outputStream.toByteArray();
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
YourRequest yourRequest = new YourRequest();
yourRequest.setFileName("test.jpg");
yourRequest.setPicture(encodedImage);
return mPostRequests.upload(yourRequest);
}finally {
if(bmp!=null)
bmp.recycle();
}
}
}
4.Execute
public void uploadMethod()
{
Api api=new Api();
api.upload("path").execute().body();// it is sync operation you can use eneque() for async
}
您以String格式(Base64)上传图片,因此您可以将此String放入pojo对象。