马会东的博客

马会东的博客

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

转载:http://liuzhichao.com/p/1707.html

OkHttp–支持SPDY协议的高效HTTP库

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

 

posted on 2015-05-20 22:07  马会东  阅读(598)  评论(0编辑  收藏  举报