标签:
RequestInterceptor 请求拦截器
RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("User-Agent", "Retrofit-Sample-App"); } };
RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://api.github.com") .setRequestInterceptor(requestInterceptor) .build();
class MyErrorHandler implements ErrorHandler { @Override public Throwable handleError(RetrofitError cause) { Response r = cause.getResponse(); if (r != null && r.getStatus() == 401) { return new UnauthorizedException(cause); } return cause; //返回值不能是null,否则运行是会出现异常. } }
RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://api.github.com") .setErrorHandler(new MyErrorHandler()) .build();
RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint("https://api.github.com") .build();
不同于拦截器或者ErrorHandler,可以在RestAdapter生命周期的任何时候通过setLogLevel()添加或者更改logging level.
public class JacksonConverter implements Converter { // Constructor ... @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { JavaType javaType = objectMapper.getTypeFactory().constructType(type); try { return objectMapper.readValue(body.in(), javaType); } catch (IOException e) { throw new ConversionException(e); } } @Override public TypedOutput toBody(Object object) { try { String charset = "UTF-8"; return new JsonTypedOutput(objectMapper.writeValueAsString(object).getBytes(charset), charset); } catch (IOException e) { throw new AssertionError(e); } } ... // JsonTypedOutput implementation }
private static class JsonTypedOutput implements TypedOutput { private final byte[] jsonBytes; private final String mimeType; JsonTypedOutput(byte[] jsonBytes, String encode) { this.jsonBytes = jsonBytes; this.mimeType = "application/json; charset=" + encode; } @Override public String fileName() { return null; } @Override public String mimeType() { return mimeType; } @Override public long length() { return jsonBytes.length; } @Override public void writeTo(OutputStream out) throws IOException { out.write(jsonBytes); } }
标签:
原文地址:http://www.cnblogs.com/laiqurufeng/p/4484916.html