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. 几种常用单片机I/O口线的驱动能力

    摘要: 详细分析了几种常见单片机的I/O口结构,并据此分析其驱动能力大小 在控制系统中,经常用单片机的I/O口驱动其他电路.几种常用单片机I/O口驱动能力在相关的资料中的说法是:GMS97C2051. ...

  2. Qt5.3.0 for android windows平台下搭建及demo(虫子的博客)

    ----我的生活,我的点点滴滴!! 部门领导突然心血来潮,想在android平台上做应用,但是我们大多产品属于嵌入式(本吊只负责写写应用,苦比的被强行顶过来搞这,由于这还得领导吵了一架,架虽然吵完了, ...

  3. 利用代码改变世界 #AzureDev

    毫无疑问,开发人员是 //build/ 2013 的主角.开发人员是我们这个行业的心脏和灵魂,我们很感谢他们所做的一切.在 Satya Nadella 走上讲台发表第 2 天的主题演讲之前,我们播放了 ...

  4. Codeforces 339E

    #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> # ...

  5. C++关键字之static

    一.面向过程设计中的static 1.静态全局变量 在全局变量前,加上关键字static,该变量就被定义成为一个静态全局变量.我们先举一个静态全局变量的例子,如下: [cpp]   #include& ...

  6. Oracle Bills of Material and Engineering Application Program Interface (APIs)

    In this Document Goal   Solution   1. Sample Notes for BOM APIs   2. Datatypes used in these APIs   ...

  7. ORACLE EBS BOM 展开(使用标准程序bompexpl.exploder_userexit展开)

    create or replace package cux_bom_pub is PROCEDURE bom_expand_to_temp( p_organization_id number, p_i ...

  8. 关于debug和release 以及new 和delete

    题目:给出一组字符串 输入:"ate","eat","Eat","new","ENW",“wha” ...

  9. win7 64位系统调试zkemkeeper.dll出错误解决

    最近调用中控科技dll文件总是会出现上问题,网上找了大半天都没解决? 今天终于解决,原来是旧的dll文件是有问题,在中控网站上下载了最新的sdk(64位),解压,找到sdk的全部文件夹. 全选所有的: ...

  10. OpenCV系列--摄像头控制的简单代码

    操作系统:windows xp 开发工具:VS2008 opencv版本:2.1.0 依赖库:OpenCV2.1\lib\highgui.lib #include "cv.h" # ...