Android OKHttp介绍与使用(二)

Android OKHttp介绍与使用(一)中只是简单的介绍了一下OKHttp并贴了一个小Demo来尝试一下OkHttp。在本篇博客中将对OKHttp的使用进行系统的介绍。

OKHttp简单体验

使用前提:
Android Studio添加依赖库

  compile 'com.squareup.okio:okio:1.9.0'
  compile 'com.squareup.okhttp3:okhttp:3.4.1'

Ecplise:
https://github.com/square/okhttp
下载最新jar

一般Get请求三步:

(1)创建OKHttpClient
OkHttpClient client = new OkHttpClient();

(2)创建Request
Request request = new Request.Builder().url(url).build();
(3)回调并执行或加入请求行列
client.newCall(request).execute()
或者client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
    }
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
   }
   }
})

例:
http://blog.csdn.net/danfengw/article/details/52189581

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

一般Post请求

与get请求相比多了一个RequestBody 用来传递参数

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

OKHttp具体使用

添加请求头

Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .addHeader("Accept", "application/vnd.github.v3+json")
        .build();

请求超时

  client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();

Get

同步Get请求

下面的response.body().string()方法对于下载小文件而言是一种比较方便且高效的方式。但是对于大文件(大于1M),最好采用inputstream输入流的形式。这是因为String方式会将下载的文件放在内存中占用空间。

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }

    System.out.println(response.body().string());
  }
异步Get请求
  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }

        System.out.println(response.body().string());
      }
    });
  }
同步请求与异步请求

两者区别在于一个直接调用execute方法一个调用enqueue方法。

Post

Posting a String

适用于小于1M的文本传输

  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    String postBody = "aaa";

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
Post File
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();

    Response response = client.newCall(request).execute();

OKHttp的用法不止这些,可以在Github上面找到OkHttp再研究研究。我想说的是从上面的代码中可以看出来要在项目中使用OKHttp还需要我们自己进行封装才行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值