【发布时间】:2018-02-20 17:21:14
【问题描述】:
我是使用 Retrofit 的新手,我想将任何文件的字节数组发送到服务器,因为我总是收到来自服务器的失败响应,并且我成功地使用 Volley 和 HttpUrlConnection 发布文件。现在请帮助我,这是我的代码 sn-p。
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。它有敏感数据。但是当我将图像或视频文件转换为字节数组并将该字节数组发送到服务器时,我总是得到服务器的失败响应。
【问题讨论】:
-
我想使用 Retrofit2 发布,我已经使用 HttpUrlConnection 完成了。