Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。

OkHttp是一个高效的HTTP库:

  • 支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
  • 如果SPDY不可用,则通过连接池来减少请求延时
  • 无缝的支持GZIP来减少数据流量
  • 缓存响应数据来减少重复的网络请求

会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。

使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。

Examples

下面的示例请求一个URL并答应出返回内容字符.

package com.squareup.okhttp.guide;

import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class GetExample {
OkHttpClient client = new OkHttpClient(); void run() throws IOException {
String result = get(new URL("https://raw.github.com/square/okhttp/master/README.md"));
System.out.println(result);
} String get(URL url) throws IOException {
HttpURLConnection connection = client.open(url);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null) in.close();
}
} byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return out.toByteArray();
} public static void main(String[] args) throws IOException {
new GetExample().run();
}
}

下面的代码通过Post发送数据到服务器:

package com.squareup.okhttp.guide;

import com.squareup.okhttp.OkHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class PostExample {
OkHttpClient client = new OkHttpClient(); void run() throws IOException {
byte[] body = bowlingJson("Jesse", "Jake").getBytes("UTF-8");
String result = post(new URL("http://www.roundsapp.com/post"), body);
System.out.println(result);
} String post(URL url, byte[] body) throws IOException {
HttpURLConnection connection = client.open(url);
OutputStream out = null;
InputStream in = null;
try {
// Write the request.
connection.setRequestMethod("POST");
out = connection.getOutputStream();
out.write(body);
out.close(); // Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
in = connection.getInputStream();
return readFirstLine(in);
} finally {
// Clean up.
if (out != null) out.close();
if (in != null) in.close();
}
} String readFirstLine(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
return reader.readLine();
} String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
} public static void main(String[] args) throws IOException {
new PostExample().run();
}
}

参考:

http://square.github.io/okhttp/

http://android-developers.blogspot.com/2011/09/androids-http-clients.html

OkHttp–支持SPDY协议的高效HTTP库的更多相关文章

  1. 关于OkHttp–支持SPDY协议的高效HTTP库 com.squareup.okhttp

    转载:http://liuzhichao.com/p/1707.html OkHttp–支持SPDY协议的高效HTTP库 柳志超博客 » Program » Andriod » OkHttp–支持SP ...

  2. Visual Studio 2015 编译生成支持HTTPS协议的libcurl静态库

    由于之前的工作需要使用libcurl 开源项目库 在各种研究后发现无法使用HTTPS协议 后来经过各种翻阅文档,发现需要OpenSSL支持,这个需要自己下载并自己编译生成 lib 或者 dll 至于O ...

  3. HTTP代理与SPDY协议(转)

    原文出处: fqrouter HTTP代理是最经典最常见的代理协议.其用途非常广泛,普遍见于公司内网环境,一般员工都需要给浏览器配置一个HTTP代理才能访问互联网.起初,HTTP代理也用来翻越“功夫网 ...

  4. Ubuntu 12.04 LTS 下配置 apache支持SPDY, 使用wireshark 抓包分析SPDY 协议

    1.安装apache sudo apt-get install apache2 root@ubuntu:/etc/apache2/mods-enabled# apache2 -v Server ver ...

  5. Raknet是一个基于UDP网络传输协议的C++网络库(还有一些其它库,比如nanomsg,fastsocket等等)

    Raknet是一个基于UDP网络传输协议的C++网络库,允许程序员在他们自己的程序中实现高效的网络传输服务.通常情况下用于游戏,但也可以用于其它项目. Raknet有以下好处: 高性能 在同一台计算机 ...

  6. 【转】SPDY协议

    SPDY协议 - v3 原文:SPDY Protocol - Draft 3 翻译:邱鹏滔(QQ: 95350530,主页:www.fireflysource.com) 1 概述 HTTP协议的瓶颈在 ...

  7. CentOS6.5 下在Nginx中添加SSL证书以支持HTTPS协议访问

    参考文献: 1. NginxV1.8.0安装与配置 2. CentOS下在Nginx中添加SSL证书以支持HTTPS协议访问 3. nginx配置ssl证书的方法 4.nginx强制使用https访问 ...

  8. Netty 系列九(支持UDP协议).

    一.基础知识 UDP 协议相较于 TCP 协议的特点: 1.无连接协议,没有持久化连接:2.每个 UDP 数据报都是一个单独的传输单元:3.一定的数据报丢失:4.没有重传机制,也不管数据报是否可达:5 ...

  9. Python内置的urllib模块不支持https协议的解决办法

    Django站点使用django_cas接入SSO(单点登录系统),配置完成后登录,抛出“urlopen error unknown url type: https”异常.寻根朔源发现是python内 ...

随机推荐

  1. FLASH MAGIC LPC ISP下载方式说明

    硬件:EASYARM2131 开发板软件:FLASH MAGIC     下载地址:http://www.flashmagictool.com/程序:Demo2131.hex LPC的ISP下载方式, ...

  2. .Net中String和StringBuilder的区别

    String对象是不可变的而StringBuilder则不是这样,可以方便的Append进行扩展. 比如:string aa="123456",那么aa就会在内存中占用一块能放下这 ...

  3. android,在fragment中使用listview,不使用listfragment

    public class LeftFragment extends Fragment{ private ListView listView; @Override public View onCreat ...

  4. Redis 介绍与使用

    数据库主要类型有对象数据库,关系数据库,键值数据库等等,对象数据库太超前了,现阶段不提也罢:关系数据库就是平常说的MySQL,PostgreSQL这些熟的不能再熟的东西,至于键值数据库则是本文要着重说 ...

  5. 关于ztree打开关闭所有节点,选中指定id节点

    var isOneByOneExpand=false;//是否递归展开 //展开节点 function expendNode(nodeId){ var node = treeObj.getNodeBy ...

  6. 如何使用dynamic

    DataTable dt = new DataTable("TableOne"); dt.Columns.Add("ID", typeof(int));     ...

  7. 裸的单调队列-poj-2823-Sliding Window

    题目链接: http://poj.org/problem?id=2823 题目意思: 给n个数,求连续区间长度为k的最大和最小值. 解题思路: 裸的单调队列不解释,用两个队列保存. 代码: #incl ...

  8. Love Hotels and Unicode[转]

    原文地址:http://www.reigndesign.com/blog/love-hotels-and-unicode/ 讲得挺通俗的一篇文章 On Sunday 28 October I atte ...

  9. android webview点击返回键返回上一级activity

    android webview点击返回键返回上一个activity @Override public boolean onKeyDown(int keyCode, KeyEvent event) { ...

  10. 用C++编写程序,输出两个字符串的最大公共子字符串

      #include<iostream> #include<string> using namespace std; int main() { string s_l,s_sh; ...