gpt4 book ai didi

android - 使用 Retrofit 2 上传文件时出错

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:00 24 4
gpt4 key购买 nike

我正在尝试使用 Retrofit 2 将文件(图片)上传到服务器。我正在关注 tutorial乍一看这似乎很容易,但对我来说却行不通......

当我调用 API 函数时,我总是得到这个错误:

W/System.err: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
W/System.err: at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:190)
W/System.err: at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
W/System.err: at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
W/System.err: at java.lang.reflect.Proxy.invoke(Proxy.java:393)
W/System.err: at com.plante.android.cobalt.fragment.FragmentIncidentPlan.uploadFile(FragmentIncidentPlan.java:575)

这是我的 API 调用:

@Multipart
@POST(Constants.URL_UPLOAD)
Call<ResponseBody> upload(@Part RequestBody description,
@Part MultipartBody.Part file);

这是我用来上传文件的方法:

private void uploadFile(String path) {
// create upload service client

// use the FileUtils to get the actual file by uri
File file = new File(path);
Log.e(TAG, file.getAbsolutePath());

// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);

// finally, execute the request
Call<ResponseBody> call = cobaltServices.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}

最佳答案

Exceptions 说第一个 @Part 不需要在注解中有名字。

@Multipart
@POST(Constants.URL_UPLOAD)
Call<ResponseBody> upload(@Part RequestBody description,
@Part MultipartBody.Part file);

关于android - 使用 Retrofit 2 上传文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com