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 }
新闻热点
疑难解答