我正在尝试使用Retrofit
发送音频文件,但ResponseBody
始终为空,状态为500 internal server error
,我尝试了很多不同的东西,但没有任何工作
体
标题
我的客户:
public class AudioClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(context.getString(R.string.base_url)).client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
addAudioComment方法:
@Multipart
@POST("api/Comment/AddSoundComment")
Call<AudioComment> addAudioComment(@Header("Authorization") String contentRange,
@Part("referenceType") RequestBody ReferenceType,
@Part("referenceId") RequestBody ReferenceID,
@Part("parentId") RequestBody ParentID,
@Part MultipartBody.Part AudioComment);
请求:
File audioFile = new File(mRecordedFilePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("audio/*"), audioFile);
audioPart = MultipartBody.Part.createFormData("AudioComment", audioFile.getName(), reqFile);
Call<AudioComment> apiCall = service.addAudioComment(String.valueOf(SharedPreferencesHelper.getLogInToken(CommentsActivity.this)),
reqRefType, reqRefId, reqParentId, audioPart);
//apiCall =service.addAudioComment();
apiCall.enqueue(new Callback<AudioComment>() {
@Override
public void onResponse(Call<AudioComment> call, Response<AudioComment> response) {
Log.i("RETROFIT", "onResponse Called");
AudioComment postResult = response.body();
}
@Override
public void onFailure(Call<AudioComment> call, Throwable t) {
String err = t.getMessage() == null ? "" : t.getMessage();
showError(R.string.service_failure);
Log.e("RETROFIT", err);
setRefreshing(false);
dismissProgress();
}
});
答案 0 :(得分:1)
就我而言,我从接口中删除了@Multipart并替换了 @part与@Body RequestBody requestBody。例如。如下所示,第二个参数是音频文件。
public interface APIInterface {
@POST(url)
Call<String> postAudioAndGetResponse(@Header("Subscription-Key") String keyValue,
@Body RequestBody requestBody,
@Query("language") String language);
}
并像上面这样调用上面的方法
File file = new File(audioFileName);
RequestBody requestBody = RequestBody.create(MediaType.parse("audio/*"), file);
Call<String> str = apiInterface.postAudioAndGetResponse(speechSubscriptionKey, requestBody,"en-IN");
成功了。 希望它能帮助某人。 :)