这是一个 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();
}
相关报文片段