android中okhttp的基本使用

首先上官网查看文档:https://square.github.io/okhttp/

概览

HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。

OkHttp是一个默认有效的HTTP客户端:

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

当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0。

使用OkHttp很简单。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。

OkHttp支持Android 2.3及更高版本。对于Java,最低要求是1.7。

实例

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="doGet"
        android:onClick="doGet"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="doPost"
        android:onClick="doPost"/>

</LinearLayout>
(1)GET请求

MainActivity.java代码段

    public void doGet(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String str = get("http://www.baidu.com");
                    Log.e("GET", str);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

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

        Response response = client.newCall(request).execute();
        return response.body().string();
    }
POST请求
    public void doPost(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = bowlingJson("Jesse", "Jake");
                try {
                    String res = post("http://www.roundsapp.com/post", json);
                    Log.d("POST", res);
                } catch (IOException e) {
                    Log.e("err",String.valueOf(e));
                    e.printStackTrace();
                }
            }
        }).start();
    }

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

    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }

注意事项

(1)需要在manifest.xml中注册网络权限
(2)网络请求不能在主线程中进行,需要新开子线程。

发布了6 篇原创文章 · 获赞 3 · 访问量 2525

猜你喜欢

转载自blog.csdn.net/qq_37208863/article/details/84762861