我想通過Retrofit2做一個多部分POST請求,在那裏我上傳到一個自定義文件的API。改造。 java.net.ProtocolException:期望的*字節,但收到*
它隨機失敗,出現此異常:
W/System.err: java.net.ProtocolException: expected 154 bytes but received 634
有誰可以把一些光就可以了?
這是我在接口代碼:
@Multipart
@POST("recordings/{id}/{rec_id}/")
Call<ResponseBody> uploadRecording(@Path("id") String id, @Path("rec_id") String rec_id, @Part MultipartBody.Part bleFile);
在構造函數中:
public ApiConnectionManager(Context con){
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
OkHttpClient.Builder client = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(loggingInterceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(con.getResources().getString(R.string.api_url)) // API url is hidden
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client.build())
.build();
this.companyAPI = retrofit.create(CompanyAPI.class);
}
,並在上傳方法:
private void uploadFile(String id, final File bleFile) {
MediaType MEDIA_TYPE = MediaType.parse("multipart/mixed");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE,bleFile);
MultipartBody.Part partFile = MultipartBody.Part.createFormData("file", bleFile.getName(), requestBody);
String recordingId = bleFile.getName().replace(".BLE","");
Call<ResponseBody> call = companyAPI.uploadRecording(id, recordingId, partFile);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG+"-Upload "+bleFile.getName(),response.message());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(TAG,"FAILED");
t.printStackTrace();
}
});
}
使用註解「@PartMap」而不是「@Part」解決了這個問題。 – kike
請問您可以將call.enqueue()添加到此答案中,以便具有相同問題的人員可以擁有一段代碼? – kike
@kike我改變了我的答案,並且還添加了如何發送字符串以外的文件。 –