学而实习之 不亦乐乎

Android:OkHttp 实现登录

2022-07-20 08:02:22

实例:登录系统

一、简介

这里演示了在主界面中点登录后,在弹出的登录界面中实现登录操作,用户信息提交后,通过消息机制判断用户登录情况。

二、代码实现

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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="accessSecret"
            android:text="@string/get" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="showLogin"
            android:text="@string/login" />
    </LinearLayout>

    <TextView
        android:id="@+id/response"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/my_border"
        android:gravity="top"
        android:textColor="#f000"
        android:textSize="16dp"
        android:padding="10dp"
        android:layout_margin="2dp" />
</LinearLayout>

2.登录界面 login.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"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="16sp"
            android:text="@string/name" />

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="16sp"
            android:text="@string/pass" />

        <EditText
            android:id="@+id/pass"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"/>
    </LinearLayout>
</LinearLayout>

3.MainActivity.java

public class MainActivity extends Activity {
    private TextView response;
    private OkHttpClient okHttpClient;

    static class MyHandler extends Handler {
        private WeakReference<MainActivity> mainActivity;

        MyHandler(WeakReference<MainActivity> mainActivity) {
            this.mainActivity = mainActivity;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                // 使用response文本框显示服务器响应信息
                mainActivity.get().response.setText(msg.obj.toString());
            }
        }
    }

    private Handler handler = new MyHandler(new WeakReference<>(this));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        response = findViewById(R.id.response);
        // 创建默认的OkHttpClient对象
        // okHttpClient = OkHttpClient()
        final Map<String, List<Cookie>> cookieStore = new HashMap<>();
        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
                        cookieStore.put(httpUrl.host(), list);
                    }

                    @Override
                    public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
                        List<Cookie> cookies = cookieStore.get(httpUrl.host());
                        return cookies == null ? new ArrayList<>() : cookies;
                    }
                }).build();
    }

    public void accessSecret(View source) {
        new Thread(() ->
        {
            String url = "http://192.168.1.88:8888/foo/secret.jsp";
            // 创建请求
            Request request = new Request.Builder().url(url).build();  // ①
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();  // ②
                Message msg = new Message();
                msg.what = 0x123;
                msg.obj = response.body().string().trim();
                handler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void showLogin(View source) {
        // 加载登录界面
        View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
        // 使用对话框供用户登录系统
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("登录系统").setView(loginDialog)
                .setPositiveButton("登录", (dialog, which) ->
                {
                    // 获取用户输入的用户名、密码
                    String name = ((EditText) loginDialog.findViewById(R.id.name))
                            .getText().toString();
                    String pass = ((EditText) loginDialog.findViewById(R.id.pass))
                            .getText().toString();
                    String url = "http://192.168.1.88:8888/foo/login.jsp";
                    FormBody body = new FormBody.Builder().add("name", name)
                            .add("pass", pass).build();  //③
                    Request request = new Request.Builder().url(url)
                            .post(body).build();  //④
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback()  // ⑤
                    {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            Looper.prepare();
                            Toast.makeText(MainActivity.this,
                                    response.body().string().trim(), Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    });
                }).setNegativeButton("取消", null).show();
    }
}