改造.java.net.ProtocolException:期望*字节但收到*

kik*_*ike 8 rest android retrofit2

我正在尝试通过Retrofit2执行Multipart POST请求,我将API上传到自定义文件.

它随机失败,出现此异常:

W/System.err: java.net.ProtocolException: expected 154 bytes but received 634
Run Code Online (Sandbox Code Playgroud)

有人能说些什么吗?

这是我在界面中的代码:

@Multipart
@POST("recordings/{id}/{rec_id}/")
Call<ResponseBody> uploadRecording(@Path("id") String id, @Path("rec_id") String rec_id, @Part MultipartBody.Part bleFile);
Run Code Online (Sandbox Code Playgroud)

在构造函数中:

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);
}
Run Code Online (Sandbox Code Playgroud)

并在上传方法:

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();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

kik*_*ike 3

研究了一段时间这个问题后,我意识到文件的内容总是在变化(因为它是传感器的输出)。

这意味着检查HEAD的文件和检查BODY的文件可能不包含相同的数据(因此长度不同),从而导致不匹配。

我解决了这个问题,创建了文件的副本并发送它(副本)而不是原始文件。