Android OKHttp介绍与使用(二)

    xiaoxiao2025-01-09  9

    在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还需要我们自己进行封装才行。

    转载请注明原文地址: https://ju.6miu.com/read-1295317.html
    最新回复(0)