学而实习之 不亦乐乎

OkHttp使用(一):基本用法

2021-12-02 08:34:33

一、简介

虽然 HttpURLConnection 来处理网络请求已经非常好用,但 OkHttp 在 Android 开发中也有很高的使用率,甚至可以说有过之而无不及。

二、用法

1.添加 OkHttp 库的依赖

compile 'com.squareup.okhttp3:okhttp:3.4.1'

2.创建 OkHttp 实例

OkHttpClient client = new OkHttpClient();

3.构建 OkHttp 请求

Request request = new Request.Builder()
        .url(address)
        .build    

4.创建一个 Call 对象发送请求

client.newCall(request).enqueue(callback);

5.获取返回的数据

如果希望获得返回的是字符串,则可以使用
String responseData = response.body().string();

如果需要的是字节数组,则使用
response.body().bytes()

如果需要的是输入流,则使用
response.body().byteStream()

可以通过以上方法构建更为复杂的请求,如:
RequestBody requestBody = new FormBody.Builder()
        .add("username","admin")
        .add("password","123456")
        .build();

Request request = new Request.Builder()
        .url(address)
        .post(requestBody)
        .build();

三、实例:访问网页并显示

1.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>

2.MainActivity.java

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 = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);

    }

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

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            // 指定访问的服务器地址是电脑本机
                            .url("http://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


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