Retrofit 2.0-beta-2 is adding literal quotes to MultiPart values

自作多情 提交于 2019-11-28 11:53:49
Loyea

This is because it's running through the JSON converter.

Solution1: use RequestBody instead of String

public interface ApiInterface {
    @Multipart
    @POST("user/login/")
    Call<SessionToken> userLogin(@Part("username") RequestBody username, @Part("password") RequestBody password);
}

Build RequestBody:

RequestBody usernameBody = RequestBody.create(MediaType.parse("text/plain"), usernameStr);
RequestBody passwordBody = RequestBody.create(MediaType.parse("text/plain"), passwordStr);

Launch network operation:

 retrofit.create(ApiInterface.class).userLogin(usernameBody , passwordBody).enqueue()....

Solution2: Create a custom ConverterFactory to dispose String part value.

For: Retrofit2 final release not beta. (com.squareup.retrofit2:retrofit:2.0.0)

Create your StringConverterFactory:

public class StringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

public static StringConverterFactory create() {
    return new StringConverterFactory();
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (String.class.equals(type)) {
        return new Converter<ResponseBody, String>() {

            @Override
            public String convert(ResponseBody value) throws IOException {
                return value.string();
            }
        };
    }
    return null;
}

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    if(String.class.equals(type)) {
        return new Converter<String, RequestBody>() {
            @Override
            public RequestBody convert(String value) throws IOException {
                return RequestBody.create(MEDIA_TYPE, value);
            }
        };
    }

    return null;
}

}

Add to your retrofit instance:

retrofit = new Retrofit.Builder()
            .baseUrl(SERVER_URL)
            .client(client)
            .addConverterFactory(StringConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

Attention: StringConverterFactory should add before GsonConverterFactory!

then you can use String as part value directly.

You can find more information about this issue in https://github.com/square/retrofit/issues/1210

nicolas asinovich

I have the same problem, and how it solved:

1) Add to build.gradle:

compile 'com.squareup.retrofit2:converter-scalars:2.1.0' // Remember to add the same version

2) Add one line here:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create()) // this line
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(getUnsafeOkHttpClient())
                .build();
Yazon2006

I've found another one solution except those. Worked with Retrofit 2.1.0. (Rx adapter is optional here)

My retrofit interface looks like this:

@POST("/children/add")
Observable<Child> addChild(@Body RequestBody requestBody);

And in ApiManager I use it like this:

@Override
    public Observable<Child> addChild(String firstName, String lastName, Long birthDate, @Nullable File passportPicture) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("first_name", firstName)
                .addFormDataPart("last_name", lastName)
                .addFormDataPart("birth_date", birthDate + "");

        //some nullable optional parameter
        if (passportPicture != null) {
            builder.addFormDataPart("certificate", passportPicture.getName(), RequestBody.create(MediaType.parse("image/*"), passportPicture));
        }
        return api.addChild(builder.build());
    }

It is similar to Solution1 from Loyea but I think that it's little a bit more elegant.

What about to do in that way?

RequestBody caption = RequestBody.create(MediaType.parse("text/plain"), new String("caption"));

Here is how to resolve it,

Firstly:

 return new Retrofit.Builder()
    .baseUrl(Env.GetApiBaseUrl())
    .addConverterFactory(new GsonStringConverterFactory())
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(getHttpClient())
    .build();

Create a CustomConverter like this one, this is needed by Retrofit 2, unless some fix the "feature" added in v2.

public class GsonStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    @Override
    public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        if (String.class.equals(type))// || (type instanceof Class && ((Class<?>) type).isEnum()))
        {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}
cyberjaime45

If your UI is showing your responses with quotes, you can use getAsString instead of toString

Ashwani jaggi

I don't know if it is too late, but we can also send requests with RequestBody.

Example:

public interface ApiInterface {
   @Multipart
   @POST("user/login/")
   Call<SessionToken> userLogin(@Part("username") String username, @Part("password") String password);
}

We can convert as below:

public interface ApiInterface {
   @Multipart
   @POST("user/login/")
   Call<SessionToken> userLogin(@Part("username") RequestBody username, @Part("password") String password);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!