zoukankan      html  css  js  c++  java
  • Android-HttpURLConnection-Get与Post请求登录功能

    HttpURLConnection 在这请求方式是Java包中的;

    AndroidManifest.xml配置权限:

       <!-- 访问网络是危险的行为 所以需要权限 -->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <!-- 设置壁纸是危险的行为 所以需要权限 -->
        <uses-permission android:name="android.permission.SET_WALLPAPER" />

    MainActivity7.java :

    package liudeli.async;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;
    
    public class MainActivity7 extends Activity implements View.OnClickListener {
    
        private EditText etName;
        private EditText etPwd;
        private Button btLogin;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main7);
    
            etName = findViewById(R.id.et_name);
            etPwd = findViewById(R.id.et_pwd);
            btLogin = findViewById(R.id.bt_login);
    
            btLogin.setOnClickListener(this);
        }
    
        // 请求服务器的地址
        private final String PATH = "http://127.0.0.1:8080/LoginServlet";
    
        @Override
        public void onClick(View v) {
            // 拼装参数
            final Map<String, String> map = new HashMap<>();
            map.put("name", etName.getText().toString());
            map.put("pwd", etPwd.getText().toString());
    
            // 联网操作必须开启线程,执行异步任务
            new Thread(){
    
                @Override
                public void run() {
                    super.run();
    
                    try {
    
                        // Get请求方式,参数操作是拼接在链接
                        loginByGet(PATH, map);
    
                        // Post请求方式,参数操作是封装实体对象
                        loginByPost(PATH, map);
    
                    } catch (Exception e) {
                        e.printStackTrace();
                        threadRunToToast("登录是程序发生异常");
                    }
                }
    
            }.start();
        }
    
        /**
         * HttpURLConnection Get 方式请求
         * @param path 请求的路径
         * @param map  请求的参数
         *                       拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
         */
        private void loginByGet(String path, Map<String, String> map) throws Exception{
            // 拼接路径地址 拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
            StringBuffer pathString = new StringBuffer(path);
            pathString.append("?");
            
            // 迭代遍历Map
            for (Map.Entry<String, String> mapItem : map.entrySet()) {
                String key = mapItem.getKey();
                String value = mapItem.getValue();
    
                // name=zhangsan&
                pathString.append(key).append("=").append(value).append("&");
            }
            // name=zhangsan&pwd=123456& 删除最后一个符号&  删除后:name=zhangsan&pwd=123456
            pathString.deleteCharAt(pathString.length() - 1);
            // 最后完整路径地址是:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
    
            // 第一步 包装网络地址
            URL url = new URL(pathString.toString());
    
            // 第二步 打开连接对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    
            // 第三步 设置连接超时时长
            httpURLConnection.setConnectTimeout(5000);
    
            // 第四步 设置请求方式Get
            httpURLConnection.setRequestMethod("GET");
    
            // 第五步 发生请求 ⚠注意:只有在>>httpURLConnection.getResponseCode(); 才向服务器发请求
            int responseCode = httpURLConnection.getResponseCode();
    
            // 第六步 判断请求码是否成功
            // 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
            if(responseCode == HttpURLConnection.HTTP_OK) {
    
                // 第七步 获取服务器响应的流
                InputStream inputStream = httpURLConnection.getInputStream();
    
                byte[] bytes = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
                while (-1 != (len = inputStream.read())) {
                    // 把存取到bytes的数据,写入到>>ByteArrayOutputStream
                    bos.write(bytes, 0, len);
                }
    
                // 第六步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的  success代表登录成功
                String loginResult = bos.toString();
                if ("success".equals(loginResult)) {
    
                    // 不能子在子线程中Toast
                    // Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
    
                    threadRunToToast("登录成功");
    
                } else {
                    // 不能子在子线程中Toast
                    // Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
    
                    threadRunToToast("登录失败");
                }
    
                // 第七步 关闭流
                inputStream.close();
                bos.close();
    
            } else {
                // 不能子在子线程中Toast
                // Toast.makeText(this, "登录失败,请检查网络!", Toast.LENGTH_SHORT).show();
                threadRunToToast("登录失败,请检查网络!");
            }
        }
    
        /**
         * HttpURLConnection Get 方式请求
         * @param path 请求的路径
         * @param params  请求的参数
         *                       路径:http://127.0.0.1:8080/LoginServlet
         *
         *                       参数:
         *                            name=zhangsan
         *                            pwd=123456
         */
        private void loginByPost(String path, Map<String, String> params) throws Exception {
    
            // ------------------------------------------------ 以下是实体拼接帮助
    
            /**
             * 拼实体 注意⚠️:是需要服务器怎么配置  这里就要怎么拼接 例如:user.name=zhangsan&user.pwd=123
             * 注意:⚠ 这不是访问服务器的地址,这是拼接实体
             */
            StringBuilder paramsString = new StringBuilder();
            for(Map.Entry<String, String> entry: params.entrySet()){
                paramsString.append(entry.getKey());
                paramsString.append("=");
                paramsString.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                paramsString.append("&");
            }
            /**
             * user.name=zhangsan&user.pwd=123& 删除最后一个符号&  删除后:user.name=zhangsan&user.pwd=123
             * 注意:⚠ 这不是访问服务器的地址,这是拼接实体
             */
            paramsString.deleteCharAt(paramsString.length() - 1);
    
            // 理解为实体
            byte[] entity = paramsString.toString().getBytes();
    
    
            // ------------------------------------------------ 以下是 HttpURLConnection Post 访问 代码
    
            // 第一步 包装网络地址
            URL url = new URL(path);
    
            // 第二步 打开连接对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
            // 第三步 设置连接超时时长
            conn.setConnectTimeout(5000);
    
            // 第四步 设置请求方式 POST
            conn.setRequestMethod("POST");
    
            /**
             * 第五步 设置请求参数
             *        请求参数类型
             */
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 请求实体的长度(字节)
            conn.setRequestProperty("Content-Length", entity.length+"");
    
            // 第六步 允许对外输出
            conn.setDoOutput(true);
    
            // 第七步 得到输出流 并把实体输出写出去
            OutputStream os = conn.getOutputStream();
            os.write(entity);
    
            // 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
    
                // 第八步 获取服务器响应的流
                InputStream inputStream = conn.getInputStream();
    
                byte[] bytes = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
                while (-1 != (len = inputStream.read())) {
                    // 把存取到bytes的数据,写入到>>ByteArrayOutputStream
                    bos.write(bytes, 0, len);
                }
    
                // 第九步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的  success代表登录成功
                String loginResult = bos.toString();
                if ("success".equals(loginResult)) {
    
                    // 不能子在子线程中Toast
                    // Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
    
                    threadRunToToast("登录成功");
    
                } else {
                    // 不能子在子线程中Toast
                    // Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
    
                    threadRunToToast("登录失败");
                }
    
                // 第十步 关闭流
                inputStream.close();
                bos.close();
            }
        }
    
        /**
         * 在 主线程 子线程 中提示,属于UI操作
         */
        private void threadRunToToast(final String text) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    activity_main7.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:padding="20dp">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="姓名"
                />
    
            <EditText
                android:id="@+id/et_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                />
    
        </LinearLayout>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密码"
                />
    
            <EditText
                android:id="@+id/et_pwd"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                />
    
        </LinearLayout>
    
        <Button
            android:id="@+id/bt_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:text="login"
            />
    
    </LinearLayout>

  • 相关阅读:
    以太坊:深入理解Solidity-Solidity v0.5.0 重大更新
    以太坊:深入理解Solidity-合约
    以太坊:深入理解Solidity-表达式和控制结构
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
  • 原文地址:https://www.cnblogs.com/android-deli/p/10248270.html
Copyright © 2011-2022 走看看