Decoder
Decoder为feign请求后响应结果的解码器,可以通过decoder来进行返回我们自己想要的结果信息。同样Decoder是一个接口。
public interface Decoder {
// 解码
Object decode(Response response, Type type) throws IOException, DecodeException, FeignException;
}
Decoder接口中传入了Response的响应信息和Type返回的类型。
StringDecoder
public class StringDecoder implements Decoder {
@Override
public Object decode(Response response, Type type) throws IOException {
Response.Body body = response.body();
if (body == null) {
return null;
}
if (String.class.equals(type)) {
return Util.toString(body.asReader(Util.UTF_8));
}
throw new DecodeException(response.status(),
format("%s is not a type supported by this decoder.", type), response.request());
}
}
StringDecoder默认会将我们返回的流信息转换成字符串。
Decoder.Default
public class Default extends StringDecoder {
@Override
public Object decode(Response response, Type type) throws IOException {
// 判断响应结果是否为404或者204
if (response.status() == 404 || response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
if (byte[].class.equals(type)) {
return Util.toByteArray(response.body().asInputStream());
}
return super.decode(response, type);
}
}
默认的返回结果会判断状态码信息,如果状态码信息为404或者204不返回结果,如果返回为byte数组,则通过InputStream来进行转换为byte数组。其他情况直接返回为String的信息。