安卓中使用OkHttp發送數據請求的兩種方式(同、異步的GET、POST) 示例-- Android基礎

一、首先看一下最終效果的截圖,看看是否是你想要的,這個年代你們都很忙,開門見山很重要!

 

簡要說下,點擊不一樣按鈕能夠實現經過不一樣的方式發送OkHttp請求,並返回數據,這裏請求的是網頁,因此返回的都是些網頁的代碼。

二、下面給出代碼,代碼的實現步驟要點已經在代碼行中加了註釋,不過多贅述。

MainActivity.java:

package thonlon.example.cn.simpleokhttpdemo;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv;
    private Button btn_async_request, btn_sync_request, btn_async_post, btn_sync_post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    /**
     * 初始化視圖
     */
    public void initView() {
        tv = (TextView) findViewById(R.id.tv);
        btn_async_request = (Button) findViewById(R.id.btn_async_request);
        btn_sync_request = (Button) findViewById(R.id.btn_sync_request);
        btn_async_post = (Button) findViewById(R.id.btn_async_post);
        btn_sync_post = (Button) findViewById(R.id.btn_sync_post);

        btn_async_request.setOnClickListener(this);
        btn_sync_request.setOnClickListener(this);
        btn_async_post.setOnClickListener(this);
        btn_sync_post.setOnClickListener(this);
    }

    /**
     * 點擊事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_async_request:// 執行get方式的異步請求
                getAsyncRequest();
                break;
            case R.id.btn_sync_request://執行get方式的同步請求
                getSyncRequest();
                break;
            case R.id.btn_async_post://執行post方式的異步請求
                postAsynsRequest();
                break;
            case R.id.btn_sync_post://執行post方式的同步請求
                postSyncRequest();
                break;
        }
    }

    /**
     * 輸出內容到TextView
     * @param request
     */
    public void showRequest(final String request) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(request);
            }
        });
    }
    /**
     * 發送異步GET請求
     */
    private void getAsyncRequest() {
        //建立OkHttpClient對象
        OkHttpClient okhttpClient = new OkHttpClient();
        //建立Request對象
        Request request = new Request.Builder()
                .url("https://www.haha.mx/joke/2730898")//請求的地址,根據需求帶參
                .build();
        //建立call對象
        Call call = okhttpClient.newCall(request);
        call.enqueue(new Callback() {
            /**
             * 請求失敗後執行
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this,"異步get方式請求數據失敗!",Toast.LENGTH_LONG).show();
            }

            /**
             * 請求成功後執行
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"異步get方式請求數據成功!",Toast.LENGTH_LONG).show();
                        showRequest(res);
                    }
                });
            }
        });
    }

    /**
     * 發送同步的get請求
     */
    public void getSyncRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://hibernate.org/orm/releases/5.3/")
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    String responseResult = response.body().string();
                    showRequest(responseResult);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 發送異步post()請求
     */
    private void postAsynsRequest() {
        OkHttpClient okhttpClient = new OkHttpClient();
        FormBody.Builder formBody = new FormBody.Builder();//建立表單請求體
        formBody.add("usernam", "Thanlon");
        formBody.add("password", "123");
        Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .post(formBody.build())
                .build();
        Call call2 = okhttpClient.newCall(request);
        call2.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this,"異步post請求數據失敗!",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"post異步請求數據成功!",Toast.LENGTH_LONG).show();
                        showRequest(res);
                    }
                });
            }
        });
    }

    /**
     * 發送同步的post請求
     */
    public void postSyncRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    FormBody.Builder formBody = new FormBody.Builder();
                    formBody.add("username", "Thanlon");
                    formBody.add("password", "123");
                    Request request = new Request.Builder()
                            .url("https://www.douban.com")
                            .post(formBody.build())
                            .build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    String responseResult = response.body().string();
                    showRequest(responseResult);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="thonlon.example.cn.simpleokhttpdemo.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示請求後的信息"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.4" />

    <Button
        android:id="@+id/btn_async_request"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="發送request異步請求"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/btn_sync_request"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="發送request同步請求"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.1" />

    <Button
        android:id="@+id/btn_async_post"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="發送post異步請求"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.2" />

    <Button
        android:id="@+id/btn_sync_post"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="發送post同步請求"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.3" />

</android.support.constraint.ConstraintLayout>
相關文章
相關標籤/搜索