OkHttp的使用

OkHttp介绍

OkHttp是由鼎鼎大名的Square公司开发的,这个公司在开源事业上面贡献良多,除了OkHttp之外,还开发了像Picasso、Retrofit等著名的开源项目。OkHttp不仅在接口封装上面做得简单易用,就连在底层实现上也是自成一派,比起原生的HttpURLConnection,可以说是有过之无不及,现在已经成了广大Android开发者首选的网络通信库。OkHttp的项目地址

注意:
OkHttp最新版本需要在Android5.0以上版本也就是API水平要在21以上才可使用,否则就会一直报Error: Static interface methods are only supported starting with Android N (--min-api 24): java.util.List okhttp3.Dns.lambda$static$0(java.lang.String) 我当时搞了半天,最后换了一个API为25的,然后再搞搞就好了,所以在这里提醒一下,下面是来自OkHttp的GitHub说明

Requirements

OkHttp works on Android 5.0+ (API level 21+) and on Java 8+.

OkHttp has one library dependency on Okio, a small library for high-performance I/O. It works with >either Okio 1.x (implemented in Java) or Okio 2.x (upgraded to Kotlin).

We highly recommend you keep OkHttp up-to-date. As with auto-updating web browsers, staying >current with HTTPS clients is an important defense against potential security problems. We track the >dynamic TLS ecosystem and adjust OkHttp to improve connectivity and security.

OkHttp uses your platform’s built-in TLS implementation. On Java platforms OkHttp also supports >Conscrypt, which integrates BoringSSL with Java. OkHttp will use Conscrypt if it is the first security >provider:

Security.insertProviderAt(Conscrypt.newProvider(), 1);

The OkHttp 3.12.x branch supports Android 2.3+ (API level 9+) and Java 7+. These platforms lack >support for TLS 1.2 and should not be used. But because upgrading is difficult we will backport critical >fixes to the 3.12.x branch through December 31, 2020.

基本使用

可以去参考下OkHttp的官网
发送get请求

OkHttpClient client = new OkHttpClient();

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

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

发送post请求

public static final MediaType JSON
    = MediaType.get("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();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

使用示例(get请求)

在使用OkHttp之前,我们需要在项目中添加OkHttp的依赖。在build.gradle的dependencies中添加以下这个依赖。

implementation("com.squareup.okhttp3:okhttp:3.14.1")

同时还需要在还要在build.gradle中defaultConfig中加入

compileOptions {
    targetCompatibility = "8"
    sourceCompatibility = "8"
}

为什么要添加呢?因为我要进行编译在虚拟机上跑的时候,一直通不过Run tasks,它一直报Error: Static interface methods are only supported starting with Android N (--min-api 24): okhttp3.Request okhttp3.Authenticator.lambda$static$0(okhttp3.Route, okhttp3.Response),后面我查了一下,这是因为java8才支持静态接口方法的原因,所以可以通过在app的build.gradle文件中配置使用java8编译

然后就可以正常玩耍了,我这里是参考《第一行代码》关于OkHttp的例子来讲的(因为我刚好也在学,嘻嘻)。
首先在activity_main.xml中编写

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

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>

首先这里使用的线性布局然后设置了垂直显示,LinearLayout中很简单,一个Button来发送请求,一个ScrollView来进行显示返回数据。
然后修改MainActivity中的代码,使用了OkHttp之后,发送请求真滴比原生的HttpURLConnection简单好多~~

package com.ddu.test_network;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithHttpURLConnection();
        }
    }

    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //首先创建一个OkHttpClient的实例
                    OkHttpClient client = new OkHttpClient();
                    //如果想要发一条HTTP请求,就需要创建一个Request对象
                    Request request = new Request.Builder()
                            .url("http://www.baidu.com")
                            .build();
                    //调用OkHttpClient的newCall()方法来创建一个Call对象
                    //调用他的execute()方法来发送并获取服务器返回的数据
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 将数据显示到界面上
     * 
     * @param response 要显示的数据
     */
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }
}

然后需要在AndroidManifest中添加权限
<uses-permission android:name="android.permission.INTERNET" />,具体如下所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ddu.test_network">

    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

效果
点击按钮后,返回数据
效果
tip: 有需要代码的可以去我的码云去下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值