Android网络编程之SPDY

Android的网络编程大家基本都熟悉,Http的Get,Post请求与其他语言的开发大同小异,可以采用Android自带的网络开发包,也可以采用Apache的开源网络编程包。本文介绍一个支持SPDY的开发包 OkHttp,关于SPDY的知识,大家可以从维基百科和百度百科上面找到,基本就是增强版的Http。

OkHttp is an HTTP client that’s efficient by default:

  • SPDY support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if SPDY isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

示例代码

GET A URL

This program downloads a URL and print its contents as a string.

Full source.

    OkHttpClient client = new OkHttpClient();

    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();
      }
    }

POST TO A SERVER

This program posts data to a service.

Full source.

    OkHttpClient client = new OkHttpClient();

    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();
      }
    }

MAVEN 依赖库配置

<dependency>
  <groupId>com.squareup.okhttp</groupId>
  <artifactId>okhttp</artifactId>
  <version>1.2.0</version>
</dependency>

本文原始链接:http://blog.zhourunsheng.com/2013/08/android%e7%bd%91%e7%bb%9c%e7%bc%96%e7%a8%8b%e4%b9%8bspdy/(迁移后固定链接原样保留)

加入讨论

新评论 — 条

评论保存在本站自托管服务里,无需注册登录,填个昵称就能留言;不依赖任何第三方 Cookie 或账号。请尽量说点有用的 :)