开源网络通信库OkHttp的简单使用

本文介绍了如何使用OkHttp,一个由Square公司开发的强大的Android网络通信库。相较于HttpURLConnection,OkHttp更易用且功能更强。通过示例展示了如何使用OkHttp请求百度主页的HTML数据,强调了网络请求应在子线程中执行以避免主线程阻塞导致ANR问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OkHttp是Android发送http请求的常用方式之一,是著名Square公司开发的功能强大的开源网络通信库,深受Android开发者的喜爱,其使用比HttpURLConnection更为简单,而且功能较后者有过之而无不及。所以懂得使用OkHttp是一名优秀的Android开发者必须掌握的。以下的例子是通过OkHttp向服务端请求获取百度主页的html数据。

 

效果图:

 

一、设计main_activity.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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.think.okhttptest.MainActivity">

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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send request"
        android:layout_gravity="center"/>

</LinearLayout>

二、在app/build.gradle的dependencies中添加依赖:

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

三、在manifest.xml中添加权限:

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

四、编写MainActivity:

package com.example.think.okhttptest;

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

import java.io.IOException;

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

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=(TextView)findViewById(R.id.text_view);
        send=(Button)findViewById(R.id.button);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {   //在子线程中完成比较耗时的网络请求工作,防止ANR问题的发生
                    @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();
                            //调用主线程获取responseData的方法
                            returnDataToUI(responseData);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    public void returnDataToUI(final String response) {  //在子线程中不能进行UI操作,通过调用runOnUiThread()方法切换回主线程,然后在进行UI操作

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(response);
            }
        });
    }
}

 

总结:该例子中同学们需要注意的是多线程的问题,因为一般网络请求是比较耗时的 ,如果在主线程中进行请求的话,可能会造成主线程堵塞,导致ANR问题的发生。所以我们应该将网络请求代码放在子线程中去执行,然后通过runOnUiThread()方法将请求的数据送回主线程,再进行UI操作(注意:子线程中不能进行UI操作)。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值