在Android OKHttp介绍与使用(一)中只是简单的介绍了一下OKHttp并贴了一个小Demo来尝试一下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
(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(); }与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(); }下面的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()); }两者区别在于一个直接调用execute方法一个调用enqueue方法。
适用于小于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()); }OKHttp的用法不止这些,可以在Github上面找到OkHttp再研究研究。我想说的是从上面的代码中可以看出来要在项目中使用OKHttp还需要我们自己进行封装才行。