Retrofit
A type-safe REST client for Android and Java
Android中非常有名的网络框架
官网 :http://square.github.io/retrofit/
参考项目: http://square.github.io/okhttp/
Android 示例项目: https://github.com/goodev/RetrofitDemo
Retrofit vs Volley
http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/
提取一张图片
//API public interface ApiService { @GET("/jobs") public void getJobs(Callback<Data> callback); }
//RestClient public class RestClient { private static final String BASE_URL = "https://yourapi.host.com"; private ApiService apiService; public RestClient() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new ItemTypeAdapterFactory()) .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'") .create(); RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(BASE_URL) .setConverter(new GsonConverter(gson)) .setRequestInterceptor(new SessionRequestInterceptor()) .setClient(new OkClient(MySSLTrust.getUnsafeOkHttpClient())) .build(); apiService = restAdapter.create(ApiService.class); } public ApiService getApiService() { return apiService; } }
//MySSLTrust 的SSL信任 public class MySSLTrust { public static OkHttpClient getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } } /** * add Headers fro every request * Created by Hanks on 2015/5/18. */ public class SessionRequestInterceptor implements RequestInterceptor { @Override public void intercept(RequestFacade request) { /*request.addHeader("Accept", "application/json;versions=1"); if(isUserLoggedIn()){ request.addHeader("Authorization",getToken()); }*/ request.addHeader("Authorization","huhu="); } }