如何通过Retrofit2发送ArrayList和Multipart? 错误:预期为begin_object,但为字符串

问题描述

我是新手,现在做了一个多部分主体来上传文件。这是代码

#ApiConfig.java

public interface ApiConfig {
    @Multipart
    @POST("upload.PHP")
    Call<ServerResponse> uploadFile(@Part("details[]") ArrayList<String> details,@Part MultipartBody.Part file,@Part("file")RequestBody name);
}

#AppConfig.java

public class AppConfig {
    private static String BASE_URL = "http://192.168.1.1:8080/xampp/app/";
    private static Gson gson = new GsonBuilder()
            .setLenient()
            .create();
    public static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
}

#ServerResponse.java

public class ServerResponse {
    @Serializedname("success")
    boolean success;
    @Serializedname("message")
    String message;
    public String getMessage() {
        return message;
    }
    boolean getSuccess() {
        return success;
    }
}

#MainActivity.java

    private void uploadFile(String filePath) {
        File file = new File(filePath);

        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"),file);
        MultipartBody.Part filetoUpload = MultipartBody.Part.createFormData("file",file.getName(),requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"),file.getName());

        ArrayList<String> details = new ArrayList<>();
        details.add("name");
        details.add("id");
        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<ServerResponse> call = getResponse.uploadFile(details,filetoUpload,filename);
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call call,Response response) {
                ServerResponse serverResponse = (ServerResponse) response.body();
                if (serverResponse != null) {
                    Toast.makeText(MainActivity.this,serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this,"There was an error while uploading your file. Please try again later.",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call call,Throwable t) {
                Toast.makeText(MainActivity.this,Toast.LENGTH_SHORT).show();
            }
        });
    }

通过替换ApiConfig.java中的这一部分,一切工作正常:

Call<ServerResponse> uploadFile(@Part("details[]") ArrayList<String> details,@Part("file")RequestBody name);

只需

Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,@Part("file")RequestBody name);

我收到的错误

expected begin_object but was string

Retrofit不允许我发送带有文件的数组。请让我知道如何解决错误,并在PHP文件中接收数组。问候。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)