OkHttp和android网络请求框架的几种对比

okhttp是高性能的http库,支持同步、异步,而且实现了spdy、http2、websocket协议,api很简洁易用,和volley一样实现了http协议的缓存。picasso就是利用okhttp的缓存机制实现其文件缓存实现的很优雅,很正确,反例就是UIL(universal image loader),自己做的文件缓存,而且不遵守http缓存机制。

get请求

 OkHttpClient client = new OkHttpClient();
 String run(String url) throws IOException {
   Request request = new Request.Builder()
       .url(url)
       .build();

   Response response = client.newCall(request).execute();
   return response.body().string();
 }

Post请求

 public static final MediaType JSON
     = MediaType.parse("application/json; charset=utf-8");

 OkHttpClient client = new OkHttpClient();
 String post(String url, String json) throws IOException {
   RequestBody body = RequestBody.create(JSON, json);
   Request request = new Request.Builder()
       .url(url)
       .post(body)
       .build();
   Response response = client.newCall(request).execute();
   return response.body().string();
 }

android网络请求框架的几种对比

你可能感兴趣的:(OkHttp和android网络请求框架的几种对比)