Android Studio-okhttp获取的信息如何让显示在TextView

1.activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">



    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="请输物品名称:"
        android:inputType="textPhonetic"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="开始"
        android:onClick="start"
        />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="结果"
        android:layout_marginTop="10dp"
        />

</LinearLayout>

2.MainActivity.java

get同步方式:

package com.example.okhttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

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


public class MainActivity extends AppCompatActivity {

    public static final int UPDATE_TEXT=1;
    private TextView tvContent;
    private EditText etContent;
    private static String string;
    private static String goods;
    private static final String TAG="MainActivty";
    private final OkHttpClient mclient=new OkHttpClient();

    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what==UPDATE_TEXT){
                tvContent.setText(string);
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvContent = findViewById(R.id.tv_content);
        etContent = findViewById(R.id.et_content);
    }

    //执行一个耗时任务
   public void start(View view){
        new Thread (new Runnable(){
            @Override
            public void run(){
            	goods = etContent.getText().toString();
                get(goods);
                Message message=new Message();
                message.what=UPDATE_TEXT;
                handler.sendMessage(message);
            }
        }).start();
       Toast.makeText(this,"开启子线程请求网络!",Toast.LENGTH_SHORT).show();
    }

    private void get(String goods) {
        Request.Builder builder = new Request.Builder();
        builder.url("http://api.tianapi.com/txapi/lajifenlei/index?key=2fc5beaf8a31e04108e4a5e1d8cea0f6&word=" + goods);
        Request request = builder.build();

        Log.d(TAG, "run:" + request);

        OkHttpClient client = new OkHttpClient();


        Call call = mclient.newCall(request);

        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                string = response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:
Android Studio-okhttp获取的信息如何让显示在TextView_第1张图片
get异步方式:

package com.example.okhttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

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

public class MainActivity extends AppCompatActivity {
    public static final int UPDATE_TEXT=1;
    private TextView tvContent;
    private EditText etContent;
    private static String string;
    private static String goods;
    private static final String TAG="MainActivty";
    private final OkHttpClient mclient=new OkHttpClient();
    
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what==UPDATE_TEXT){
                tvContent.setText(string);
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvContent = findViewById(R.id.tv_content);
        etContent = findViewById(R.id.et_content);
    }

    //执行一个耗时任务
    public void start(View view){
        new Thread (new Runnable(){
            @Override
            public void run(){
            	goods = etContent.getText().toString();
                GetFun(goods,new VolleyCallback() {
                    @Override
                    public void onSuccess(String result){
                        Log.d(TAG,"onSuccess"+result);
                        Message message=new Message();
                        message.what=UPDATE_TEXT;
                        message.obj=result;
                        handler.sendMessage(message);
                    }
                });
            };
        }).start();
        Toast.makeText(this,"开启子线程请求网络!",Toast.LENGTH_SHORT).show();
    }

    public static void GetFun(String goods,final VolleyCallback callback){
        String url = "http://api.tianapi.com/txapi/lajifenlei/index?key=2fc5beaf8a31e04108e4a5e1d8cea0f6&word="+goods;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                string = response.body().string();
                callback.onSuccess(string);
                //Log.d(TAG, "onResponse: " + response.body().string());
            }
        });
    }
    private interface VolleyCallback {
        void onSuccess(String result);
    }
}

运行结果:
Android Studio-okhttp获取的信息如何让显示在TextView_第2张图片

你可能感兴趣的:(Android,Studio,okhttp,android,studio,android)