Administrator
发布于 2023-11-20 / 8 阅读
0
0

OkHttp使用步骤

OkHttp使用步骤

1.引入依赖

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

2. 创建OkHttpClient对象

OkHttpClient client = new OkHttpClient();

3.创建Request对象

Request request = new Request.Builder()
                .get()
                .url("https:www.baidu.com")
                .build();

4.创建Call

将前面的request传递进去

Call call = client.newCall(request);

5.call.execute()

根据需要调用同步或者异步请求方法

//同步调用,返回Response,会抛出IO异常

Response response = call.execute();

6.call.enqueue(Callback)

异步调用,并设置回调函数

call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        final String res = response.body().string();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                contentTv.setText(res);
            }
        });
    }
});

6.权限

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


评论