OkHttp简介(机翻)

HTTP是现代应用程序网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以使您的内容加载更快并节省带宽。OkHttp是默认情况下有效的HTTP客户端:

  • HTTP / 2支持允许对同一主机的所有请求共享一个套接字。
    • 连接池可减少请求延迟(如果HTTP / 2不可用)。
    • 透明的GZIP缩小了下载大小。
    • 响应缓存可以完全避免网络重复请求。

当网络出现问题时,OkHttp会坚持不懈:它将从常见的连接问题中静默恢复。如果您的服务具有多个IP地址,则在第一次连接失败时,OkHttp将尝试使用备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp支持现代TLS功能(TLS 1.3,ALPN,证书固定)。可以将其配置为回退以获得广泛的连接性。

使用OkHttp很容易。它的请求/响应API具有流畅的构建器和不变性。它支持同步阻塞调用和带有回调的异步调用。

OkHttp使用

配置

注意

okhttp版本为3.4.1,okio版本为1.8.0,否则在纯Java环境中会抛出异常

Caused by: java.lang.ClassNotFoundException: kotlin.TypeCastException

具体使用

Get请求

public void httpGet() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com").get().build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

Post请求

发送表单
public void httpPost() throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder().add("name", "lzw-723").build();
        Request request = new Request.Builder().url("http://www.baidu.com").post(requestBody).build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
发送JSON
public void httpPostJson(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, "{\"code\", 0}");;
        Request request = new Request.Builder().url("http://www.baidu.com").post(requestBody).build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

异步请求

 public void httpGetAsync() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com").get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    }

携带Header请求

 public void httpGetWithHeader() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
         .url("http://www.baidu.com").get().addHeader("Cookie", "xx").build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

获取响应的Header

public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com").get().build();
        Response response = client.newCall(request).execute();
        System.out.println(response.header("server"));
    }

Cookie管理

private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .cookieJar(new CookieJar() {
        @Override
        public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
            cookieStore.put(httpUrl.host(), list);
        }
        @Override
        public List<Cookie> loadForRequest(HttpUrl httpUrl) {
            List<Cookie> cookies = cookieStore.get(httpUrl.host());
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    })
    .build();

文件下载

    public void download(final String url, final String destFileDir, final String destFileName) {
        Request request = new Request.Builder().url(url).build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                //储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) dir.mkdirs();
                File file = new File(dir, destFileName);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                    }
                    fos.flush();
                    //下载完成
                } catch (Exception e) {} finally {
                    try {
                        if (is != null) is.close();
                        if (fos != null) fos.close();
                    } catch (IOException e) {}
                }
            }
        });
    }

文件上传

public ResponseBody upload(String url, String filePath, String fileName) throws Exception {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .build();
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .url(url)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response)
        return response.body();
    }

参考