OkHttp 是一個高效的HTTP庫,使用java進行編寫。適用于Android 和 Java 應用,通過它可以向服務器請求(GET)數據、發送(POST)數據 :
支持 SPDY 和連接池來減少請求延時
支持GZip來減少數據流量
支持緩存響應數據以達到減少重復的網絡請求的目的。
一下是簡單的get和post請求。
向服務器請求 (get)
String getRequest(String url) throws IOException {OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string();}
向服務器發送(post):
1 public class Test{ 2 public static final MediaType DATA 3 = MediaType.parse("text/x-markdown; charset=utf-8"); 4 5 public String getPost(String url, String json) throws IOException { 6 7 OkHttpClient client = new OkHttpClient(); 8 9 RequestBody body = RequestBody.create(DATA, json);10 11 Request request = new Request.Builder().url(url)12 13 .post(body).build();14 15 Response response = client.newCall(request).execute();16 17 return response.body().string();18 19 } 20 }
新聞熱點
疑難解答