Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

java - Android Retrofit Base64 @Body

Hi all i have this code in android 4.3 and i am using retrofit just now but server thrown me an error message "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters." When i am using retrofit

//Normal HttpClient
//Base64 String
photo = new String(b);

// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();

// Creating HTTP Post
HttpPut httpPut = new HttpPut("http://beta2.irealtor.api.iproperty.com.my.ipga.local/PhotoService/"
                    + mPropertyId + "/testWatermark"
            );

httpPut.setHeader("content-type", "application/x-www-form-urlencoded");
httpPut.setHeader("Authorization","WFdSeW8vTJ1Z3oQlBJMk53VGpaekZRY2pCd1pYSlVXU090");
httpPut.setHeader("Accept", "application/json");

httpPut.setEntity(new StringEntity(photo, "utf-8"));

HttpResponse response = httpClient.execute(httpPut);



//With retrofit
@Headers({
    "content-type:application/x-www-form-urlencoded"
})
@PUT("/PhotoService/{PROPERTYID}/{WATERMARK}") String uploadPhoto(
    @Body String photo,
    @Path("PROPERTYID") String propertyId,
    @Path("WATERMARK") String watermark);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For general object types (String included) Retrofit is going to use its Converter to serialize the value. In this case, Gson is used by default to serialize the body as JSON.

In order to upload Base64-encoded data you want to use TypedInput. This tells Retrofit that you will pass it the raw body which is already serialized and an associated Content-Type value.

@PUT("/PhotoService/{PROPERTYID}/{WATERMARK}")
String uploadPhoto(
    @Body TypedInput photo,
    @Path("PROPERTYID") String propertyId,
    @Path("WATERMARK") String watermark);

I'm going to assume that b is a byte[] in your above example. Here I'm using an existing implementation of TypedInput: TypedByteArray

TypedInput body = new TypedByteArray("application/x-www-form-urlencoded", b);
service.uploadPhoto(body, "...", "...");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...