Android OkHttp
第一次听说OkHttp是工作中,组长推荐用这个替代常用的HttpUrlConnection或者HttpClient.于是乎,我就浅阅了OkHttp的介绍,才发现又是Square的作品(工作中写的App所用到的Lib几乎全部被Square承包了).
要想深入理解OkHttp,那当然是读他的原文介绍.我这只是用通俗的语言对他做简单翻译~
OkHttp的好处:
1.通过Http/2和SPDY协议,支持对于同一个Host的所有请求共享一个Socket;
SPDY是一个好东西.是由Google推出的一套协议.意在提供Http请求的效率.他是Http的一个增强,而不是替代.
2.如果不支持SPDY协议的话,会通过连接池的方式减少请求的延时;
3.使用Gzip减少下载包的大小;
4.会缓存Response,以避免请求重复发送.
使用:
compile ‘com.squareup.okhttp:okhttp:2.3.0‘
有了Android Studio,有了Gradle后,新添加一个Lib就如此简单.
当然,你也可以通过下载Jar导入到Project里面.
例子:
1. Get a URL
1 package com.squareup.okhttp.guide; 2 3 import com.squareup.okhttp.OkHttpClient; 4 import com.squareup.okhttp.Request; 5 import com.squareup.okhttp.Response; 6 import java.io.IOException; 7 8 public class GetExample { 9 OkHttpClient client = new OkHttpClient(); 10 11 String run(String url) throws IOException { 12 Request request = new Request.Builder() 13 .url(url) 14 .build(); 15 16 Response response = client.newCall(request).execute(); 17 return response.body().string(); 18 } 19 20 public static void main(String[] args) throws IOException { 21 GetExample example = new GetExample(); 22 String response = example.run("https://raw.github.com/square/okhttp/master/README.md"); 23 System.out.println(response); 24 } 25 }
2. Post to a server
1 package com.squareup.okhttp.guide; 2 3 import com.squareup.okhttp.MediaType; 4 import com.squareup.okhttp.OkHttpClient; 5 import com.squareup.okhttp.Request; 6 import com.squareup.okhttp.RequestBody; 7 import com.squareup.okhttp.Response; 8 import java.io.IOException; 9 10 public class PostExample { 11 public static final MediaType JSON 12 = MediaType.parse("application/json; charset=utf-8"); 13 14 OkHttpClient client = new OkHttpClient(); 15 16 String post(String url, String json) throws IOException { 17 RequestBody body = RequestBody.create(JSON, json); 18 Request request = new Request.Builder() 19 .url(url) 20 .post(body) 21 .build(); 22 Response response = client.newCall(request).execute(); 23 return response.body().string(); 24 } 25 26 String bowlingJson(String player1, String player2) { 27 return "{‘winCondition‘:‘HIGH_SCORE‘," 28 + "‘name‘:‘Bowling‘," 29 + "‘round‘:4," 30 + "‘lastSaved‘:1367702411696," 31 + "‘dateStarted‘:1367702378785," 32 + "‘players‘:[" 33 + "{‘name‘:‘" + player1 + "‘,‘history‘:[10,8,6,7,8],‘color‘:-13388315,‘total‘:39}," 34 + "{‘name‘:‘" + player2 + "‘,‘history‘:[6,10,5,10,10],‘color‘:-48060,‘total‘:41}" 35 + "]}"; 36 } 37 38 public static void main(String[] args) throws IOException { 39 PostExample example = new PostExample(); 40 String json = example.bowlingJson("Jesse", "Jake"); 41 String response = example.post("http://www.roundsapp.com/post", json); 42 System.out.println(response); 43 } 44 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。