android网络访问框架OkHttp使用入门

本文介绍如何使用OkHttp框架在Android应用中实现网络请求。包括添加依赖、创建OkHttpClient实例、构建Request对象及处理响应数据的过程。通过示例展示了GET请求的具体实现。

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

虽然在android中我们可以使用java.net包中的HttpURLConnection类来访问网络,但是用起来确不是很方便,所以出现了一些网络访问框架,使得我们对网络的访问更加容易,这篇文章准备解下OkHttp这款框架的简单的使用,OkHttp是由Square公司开发的,并且OkHttp项目在github上开源,该项目的主页地址为:点击打开链接

使用OkHttp发送网络请求的流程大致如下:

1、创建一个OkHttpClient的实例 OkHttpClient client = new OkHttpClient();

2、创建一个Request对象  Request request = new Request.Builder().build(); Builder()构造器后可以跟系列的方法对请求进行设置,比如url()方法设置要发送请求的地址等。

3、调用OkHttpClient的newCall()方法来创建一个Call对象,并调用它的execute()方法来发送请求并获取服务器返回的数据  Response response = client.newCall(request).execute();   其中Response就是服务器中返回的数据可以使用

String responseText = response.body().string()获取

【注】如果是发起一条POST请求的话要先创建一个RequestBody对象来放要提交的参数,如下所示:      RequestBody requestBody = new FormBody.Builder().add("username", "tangliang").add("password", "bugaosuni").build();  然后在Request.Builder()中调用一下post方法,并将RequestBody对象传进去。其他的就和发送GET请求一样了。


下面来举个小例子,新建一个OkHttp项目:

要使用OkHttp框架,首先需要在项目中添加OkHttp库的依赖。目前最新版本为3.8.1

所以在 app/build.gradle文件中的dependencies中添加 compile 'com.squareup.okhttp3:okhttp:3.8.1'


activity_main.xml中的代码如下:

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

    <Button
        android:id="@+id/sendRequest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Requset"
        android:textAllCaps="false"/>

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

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

    </ScrollView>

</LinearLayout>

AndroidManifest.xml中的代码如下:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

由于需要访问网络,所以必须申请INTERNET权限


MainActivity中的代码如下:


package com.tangliang.okhttp;

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 {

    private TextView responseData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.sendRequest);
        responseData = (TextView) findViewById(R.id.responseData);
        sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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 responseText = response.body().string();
                    showResponse(responseText);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseData.setText(response);
            }
        });
    }
}

程序运行结果 如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值