混合APP开发的套路(6): Android发送http网络请求

本文介绍如何在Android应用中利用Bridge库实现登录界面的HTTP网络请求,并解析服务器返回的JSON数据,显示登录结果。

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

前面我们做来一个非常简单丑陋的界面,通过html页面打开一个登录窗口,这就是我们所谓的混合开发,部分功能使用原生代码来编写,另外一部分使用html编写。

今天我们要来学习Android发送http网络请求

关于http网络请求,如果我们使用最原始的方式也能实现,但是实际开发我们肯定是使用一些现成的开源内库。
我这里使用的是:
https://github.com/afollestad/bridge

1、怎么集成到项目中

看Gradle:
https://github.com/afollestad/bridge#gradle-android

这里写图片描述

点击Sync Now 开始下载。
下载完成可以在External Libraies 查看:
这里写图片描述

2、使用该内库

来到登录页面,当用户输入”用户名”和”密码之后,点击”登录”按钮,发送网络请求。
这里写图片描述

业务逻辑是在LoginActivity.java中处理的,我们前面学习过”把用户登录信息(用户名和密码)保存到SharePreferences中”:

        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 保存到SharePreferences
                SharedPreferences sharedPreferences = getSharedPreferences("users",MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("user_login_name",login_username.getText().toString());
                editor.commit();

                // 上面完成用户登录信息的保存
                // 下面跳转
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this,WebViewActivity.class);
                startActivity(intent);
            }
        });

现在我们在这里发送网络请求:

        // 给按钮组件绑定事件
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 启动一个子线程
              new  Thread(requestAPI).start();
            }
        });

点击“登录”按钮,启动一个子线程(requestAPI 方法),这个子线程完成了http请求多业务代码。

    /**
     * 发送网络请求不能在主线程,需要新开一个线程
     */
    Runnable requestAPI = new Runnable() {
        @Override
        public void run() {
            Form form = new Form().add("user_name",login_username.getText().toString())
                    .add("user_pass",login_pwd.getText().toString());

            try {
                Request request = Bridge.post("http://192.168.15.138/user.php").body(form).request();
                Response response = request.response();
                if (response.isSuccess()){
                    // 服务器响应的数据转json
                    JSONObject jsonObject = response.asJsonObject();

                    Looper.prepare(); //创建消息队列

                    // 对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                    builder.setTitle("登录结果");
                    builder.setMessage(jsonObject.get("message").toString());
                    builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss(); // 关闭对话框
                        }
                    });
                    builder.show(); // 不要忘记最后展示对话框

                    Looper.loop(); //进入消息循环

                }else{
                    // http请求失败

                }
            } catch (BridgeException e) {
                e.printStackTrace();
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

注意这部分代码,不仅有使用Bridge这个第三方的http内库,还有Android系统自带的对话框代码AlertDialog

其他知识:在子线程弹出对话框要注意的点

简单理解下:Android系统内部有相应的消息队列和消息循环机制
如果想让该线程具有消息队列和消息循环,需要在线程中首先调用Looper.prepare()来创建消息队列,然后调用Looper.loop()进入消息循环

3、演示
这里写图片描述

至此这个LoginActivity.java(登录界面)全部代码如下:

package com.example.dev.firtapp;


import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.afollestad.bridge.Bridge;
import com.afollestad.bridge.BridgeException;
import com.afollestad.bridge.Form;
import com.afollestad.bridge.Request;
import com.afollestad.bridge.Response;

import org.json.JSONException;
import org.json.JSONObject;

import static android.content.SharedPreferences.*;

public class LoginActivity extends AppCompatActivity {

    Button login_btn;
    EditText login_username;
    EditText login_pwd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置布局
        this.setContentView(R.layout.login);

        // 拿到相关组件
        login_btn = (Button)findViewById(R.id.login_btn);
        login_username = (EditText)findViewById(R.id.login_username);
        login_pwd = (EditText)findViewById(R.id.login_pwd);

        // 给按钮组件绑定事件
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 启动一个子线程
              new  Thread(requestAPI).start();
            }
        });
    }

    /**
     * 发送网络请求不能在主线程,需要新开一个线程
     */
    Runnable requestAPI = new Runnable() {
        @Override
        public void run() {
            Form form = new Form().add("user_name",login_username.getText().toString())
                    .add("user_pass",login_pwd.getText().toString());

            try {
                Request request = Bridge.post("http://192.168.15.138/user.php").body(form).request();
                Response response = request.response();
                if (response.isSuccess()){
                    // 服务器响应的数据转json
                    JSONObject jsonObject = response.asJsonObject();

                    Looper.prepare(); //创建消息队列

                    // 对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                    builder.setTitle("登录结果");
                    builder.setMessage(jsonObject.get("message").toString());
                    builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss(); // 关闭对话框
                        }
                    });
                    builder.show(); // 不要忘记最后展示对话框

                    Looper.loop(); //进入消息循环

                }else{
                    // http请求失败

                }
            } catch (BridgeException e) {
                e.printStackTrace();
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
}

4、服务器端
http://192.168.15.138/user.php 代码:

<?php

$result = new stdClass();
$result->message = "error username or password";
$result->status = "error";
if(isset($_POST["user_name"]) && isset($_POST["user_pass"])){
    $get_uname = trim($_POST["user_name"]);
    $get_pwd = trim($_POST["user_pass"]);
    if($get_uname=="zhangsan" && $get_pwd=="123"){
        $result->message = "login success";
        $result->status = "success";
    }
}

header("Content-type:application/json");
die(json_encode($result));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值