使用 Retrofit 发布音频文件

POSTing an audio file with Retrofit

问题是这样的。我正在发送音乐文件。我一直收到错误 422。出于这个原因,我似乎无法正确定位我的 body

这是我的控制台输出

Content-Disposition: form-data; name="Content-Disposition: form-data; 
name="audio[file]"; filename="tr.mp3""
Content-Transfer-Encoding: binary
Content-Type: audio/mpeg
Content-Length: 6028060

和我的代码

@Multipart
@Headers({"Content-Type: multipart/form-data;", "Accept:application/json, text/plain, */*"})
@POST("audios")
Call<SoundResponse> saveSound(@Part ("Content-Disposition: form-data; name=\"audio[file]\"; filename=\"tr.mp3\"") RequestBody file,
                              @Query("auth_token") String authToken);

并调用了这个方法

        RequestBody body = RequestBody.create(MediaType.parse("audio/mpeg"), file);

        GeoService.saveSound(body,SoundResponseCallback, getAuthToken());

我也找到了这个东西

在我看来,问题是该字段看起来像这样“音频 [文件]”

感谢您的帮助

我发现 question.The 解决方案的答案是必须将文件转换为字节

 private void sendFile(Uri data) {
    mParent.showProgress();
    MultipartBody.Part file = packFile(view.getContext(), "audio[file]", data);
    GeoService.saveSound(file, SoundResponseCallback, getAuthToken());
}

@Nullable
public static MultipartBody.Part packFile(@NonNull Context context, @NonNull String partName, @Nullable Uri fileUri) {
    if (fileUri == null) return null;
    ContentResolver cr = context.getContentResolver();
    String tp = cr.getType(fileUri);
    if (tp == null) {
        tp = "audio";
    }
    try {
        InputStream iStream = context.getContentResolver().openInputStream(fileUri);
        byte[] inputData = getBytes(iStream);
        RequestBody requestFile = RequestBody.create(MediaType.parse(tp), inputData);
        return MultipartBody.Part.createFormData(partName, fileUri.getLastPathSegment(), requestFile);
    } catch (Exception e) {
        return null;
    }
}

@Nullable
private static byte[] getBytes(@Nullable InputStream inputStream) throws IOException {
    if (inputStream == null) return null;
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
}