http 1.0 与 http1.1的区别
TCP连接上
1.1之后每次只需要建立一次TCP通道
http1.0每次请求都需要简历新的TCP连接,连接不能复用。
http1.1心的请求可以在上次请求建立的TCP连接之上发送,连接可以复用。
有点是减少重复进行TCP三次握手的开销,提高效率。
注意:在同一个TCP连接中,新的请求需要等到上次请求收到响应后,才能发送
URLConnection conn = url.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0");
HttpUrlConnection 与 HttpClient哪个更好
在2.3之前选择用httpClient,因为httpurlConnection关闭时会关闭长连接,
有时返回的内容长度为-1;
2.3之后,选择用HttpUrlConnection,因为HttpUrlConnection 体积小,响应速度快,减少耗电量
HttpResponseCache
HttpResponseCache是4.0以后出现测缓存框架,现在只支持HttpUrlConnection,HttpsUrlConnection,不支持DefalutHttpClient和AndroidHttpClient.
代码:
1 protected void onCreate(Bundle savedInstanceState) { 2 ... 3 4 try { 5 File httpCacheDir = new File(context.getCacheDir(), "http"); 6 long httpCacheSize = 10 * 1024 * 1024; // 10 MiB 7 HttpResponseCache.install(httpCacheDir, httpCacheSize); 8 catch (IOException e) { 9 Log.i(TAG, "HTTP response cache installation failed:" + e); 10 } 11 } 12 13 protected void onStop() { 14 ... 15 16 HttpResponseCache cache = HttpResponseCache.getInstalled(); 17 if (cache != null) { 18 cache.flush(); 19 } 20 }}