美文网首页
Retrofit2 byte[] 转换器(Java 8)

Retrofit2 byte[] 转换器(Java 8)

作者: Eniso | 来源:发表于2019-05-13 23:45 被阅读0次

    这是一个 Retrofit2 的 byte[] 转换器,基于 Java 8 编写的。如果你使用了其他版本的 Java,得不到预期结果,可能与 type == byte[].class 判断语句有关。

    • ByteArrayConverterFactory.java
    package retrofit2.converter.bytearray;
    
    import okhttp3.MediaType;
    import okhttp3.RequestBody;
    import okhttp3.ResponseBody;
    import retrofit2.Converter;
    import retrofit2.Retrofit;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Type;
    
    public class ByteArrayConverterFactory extends Converter.Factory {
    
        private static final MediaType MEDIA_TYPE = MediaType.get("application/octet-stream");
    
        public static ByteArrayConverterFactory create() {
            return new ByteArrayConverterFactory();
        }
    
        private ByteArrayConverterFactory() {
        }
    
        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(
                Type type, Annotation[] annotations, Retrofit retrofit) {
            if (!(type instanceof Class)) {
                return null;
            }
            return (type == byte[].class) ? ResponseBody::bytes : null;
        }
    
        @Override
        public Converter<?, RequestBody> requestBodyConverter(
                Type type, Annotation[] parameterAnnotations,
                Annotation[] methodAnnotations, Retrofit retrofit) {
            if (!(type instanceof Class)) {
                return null;
            }
            return (type == byte[].class) ? (Converter<byte[], RequestBody>)
                    value -> RequestBody.create(MEDIA_TYPE, value) : null;
        }
    
    }
    

    简单测试

        private static interface TestApi {
    
            @POST("/")
            public Call<ResponseBody> post(@Body byte[] body);
    
        }
    
        public static void main(String[] args) throws IOException {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://github.com/")
                    .addConverterFactory(ByteArrayConverterFactory.create())
                    .build();
            TestApi api = retrofit.create(TestApi.class);
            api.post(new byte[]{(byte) 0xab, 0x01, 0x02, (byte) 0xcd}).execute();
        }
    

    相关报文片段

    image.png

    相关文章

      网友评论

          本文标题:Retrofit2 byte[] 转换器(Java 8)

          本文链接:https://www.haomeiwen.com/subject/bzwdaqtx.html