OkHttp –Android、Java应用中的 HTTP & SPDY 客户端库

原文链接: http://blog.chengyunfeng.com/?p=489

我们通过HTTP在设备和服务器之前交换数据。高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生

OkHttp是一个高效的HTTP库:

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

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

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

OkHttp 支持 Android 2.2+;Java 1.5+。

示例

通过GET请求一个URL

下面的示例请求一个URL并答应出返回内容字符。 猛击我查看全部代码

    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 数据到服务器

下面的代码通过Post发送数据到服务器 猛击我查看全部代码

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


项目主页: OkHttp


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值