我是 Retrofit 的新手,我想将任何文件的字节数组发送到服务器,因为我总是从服务器收到失败的响应,并且我成功地使用 Volley 和 HttpUrlConnection 发布了文件。现在请帮助我,这是我的代码 fragment 。
public class ApiClientPost {
private static final String BASE_URL = "http://BASE.URL/api/";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
@Multipart
@Headers({
"content-type: multipart/form-data"
})
@POST("eclaims/UploadFiles")
Call<JsonElement> UploadFiles(@Part MultipartBody.Part body);
}
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fin);
DataInputStream dis = new DataInputStream(bis);
fileContent = toByteArray(dis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaType mediaType = MediaType.parse("video/mp4");
RequestBody requestFile =
RequestBody.create(mediaType,
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("", file.getName(),
requestFile);
ApiInterface apiInterface =
ApiClientPost.getClient().create(ApiInterface.class);
Call<JsonElement> uploadFile = apiInterface.UploadFiles(body);
uploadFile.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call,
Response<JsonElement> response) {
if (response.isSuccessful()) {
JsonElement mainResponse = response.body();
Log.d("Response ===", mainResponse.toString());
} else {
Log.e("Response ===", "Failed");
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.e("Failed ===", t.getMessage());
}
});
抱歉,我无法提供 URL。它有敏感数据。但是当我将图像或视频文件转换为字节数组并将该字节数组发送到服务器时,我总是从服务器得到失败的响应。
最佳答案
不需要转成文件,直接传byte[]
即可。
public static MultipartBody.Part toMultiPartFile(String name, byte[] byteArray) {
RequestBody reqFile = RequestBody.create(MediaType.parse("video/mp4"), byteArray);
return MultipartBody.Part.createFormData(name,
null, // filename, this is optional
reqFile);
}
关于android - 如何使用 Retrofit 2 发布字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173111/