Created
January 22, 2022 16:56
-
-
Save Zhuinden/38d57af43e22323a32642a0a5c100c5a to your computer and use it in GitHub Desktop.
ByteArrayConverterFactory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.lang.annotation.Annotation; | |
import java.lang.reflect.Type; | |
import javax.annotation.Nullable; | |
import okhttp3.MediaType; | |
import okhttp3.RequestBody; | |
import okhttp3.ResponseBody; | |
import retrofit2.Converter; | |
import retrofit2.Retrofit; | |
/** | |
* A {@linkplain Converter.Factory converter} for byte arrays to {@code application/octet-stream} bodies. | |
*/ | |
public final class ByteArrayConverterFactory | |
extends Converter.Factory { | |
public static ByteArrayConverterFactory create() { | |
return new ByteArrayConverterFactory(); | |
} | |
private ByteArrayConverterFactory() { | |
} | |
static final class ByteArrayRequestBodyConverter | |
implements Converter<byte[], RequestBody> { | |
static final ByteArrayRequestBodyConverter INSTANCE = new ByteArrayRequestBodyConverter(); | |
private static final MediaType MEDIA_TYPE = MediaType.get("application/octet-stream; charset=UTF-8"); | |
private ByteArrayRequestBodyConverter() { | |
} | |
@Override | |
public RequestBody convert(byte[] value) | |
throws IOException { | |
return RequestBody.create(MEDIA_TYPE, value); | |
} | |
} | |
static final class ByteArrayResponseBodyConverter | |
implements Converter<ResponseBody, byte[]> { | |
static final ByteArrayResponseBodyConverter INSTANCE = new ByteArrayResponseBodyConverter(); | |
@Override | |
public byte[] convert(ResponseBody value) | |
throws IOException { | |
return value.bytes(); | |
} | |
} | |
@Override | |
public @Nullable | |
Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { | |
if(type == byte[].class) { | |
return ByteArrayRequestBodyConverter.INSTANCE; | |
} | |
return null; | |
} | |
@Override | |
public @Nullable | |
Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { | |
if(type == byte[].class) { | |
return ByteArrayResponseBodyConverter.INSTANCE; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment