Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門:用 HttpURLConnection 的 GET 方式實現登錄

編輯:關於 Android 程式設計

一、HttpURLConnection 是什麼

它是 Java 標準庫自帶的 HTTP 客戶端,比 Apache HttpClient 更輕量,也是官方從 Android 4.1 起推薦的方案。幾個要點:

每個 HttpURLConnection 實例只能用來生成一次請求。用完調 disconnect() 釋放資源,但如果底層連接空閒且可複用,系統可能會保留 socket 進入連接池——這是它比每次新建連接更高效的地方。

請求結束後,關閉 InputStream 或 OutputStream 即可釋放與該實例關聯的網絡資源,對共享的持久連接沒有影響。

重要提醒:Android 4.0 之後,網絡請求必須放在子線程中,在主線程直接發請求會拋 NetworkOnMainThreadException。這是新手最常踩的坑,後面會再說。

二、效果預覽

在上一節 RelativeLayout 登錄界面的基礎上補上網絡請求邏輯。

點擊登錄後,服務器控制台會打印收到的參數:

調試時建議先用 LogCat 過濾器把噪音屏蔽掉。點擊左上角的 + 號:

填寫過濾名稱和過濾標識(Log Tag),確定即可:

之後點擊登錄按鈕,就能在 LogCat 裡看到程序打印的響應內容:

輸入錯誤的用戶名密碼時:

三、LoginActivity 完整實現

package www.csdn.net.lesson03;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private EditText et_name, et_pass;

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

        et_name = (EditText) findViewById(R.id.et_name);
        et_pass = (EditText) findViewById(R.id.et_pass);
    }

    /**
     * 通過 android:onClick="login" 綁定的點擊事件
     * @param v 被點擊的控件
     */
    public void login(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                final String userName = et_name.getText().toString();
                final String userPass = et_pass.getText().toString();

                if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
                    Toast.makeText(this, "用戶名或者密碼不能為空",
                            Toast.LENGTH_LONG).show();
                } else {
                    System.out.println("-------- 發送請求到服務器 --------");
                    // 網絡訪問必須在子線程中進行
                    new Thread() {
                        public void run() {
                            loginByGet(userName, userPass);
                        }
                    }.start();
                }
                break;

            default:
                break;
        }
    }

    /** GET 方式提交登錄請求 */
    public void loginByGet(String userName, String userPass) {
        HttpURLConnection urlConnection = null;
        try {
            // URLEncoder.encode 把字符串轉成 application/x-www-form-urlencoded 格式
            String spec = "https://172.16.237.200:8080/video/login.do?username="
                    + URLEncoder.encode(userName, "UTF-8")
                    + "&userpass=" + URLEncoder.encode(userPass, "UTF-8");

            URL url = new URL(spec);
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(5000);      // 讀超時
            urlConnection.setConnectTimeout(5000);   // 連接超時
            urlConnection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");

            // 200 成功 / 302 重定向 / 404 未找到 / 505 版本不支持
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                ByteArrayOutputStream os = new ByteArrayOutputStream();

                int len = 0;
                byte buffer[] = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }

                is.close();
                os.close();

                String result = new String(os.toByteArray());
                System.out.println("*** " + result + " ***");
            } else {
                System.out.println("-------- 連接失敗 --------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}

四、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="www.csdn.net.lesson03"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <!-- 訪問網絡的權限,少了這行必崩 -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

五、服務端 Servlet

package www.csdn.net.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userName = request.getParameter("username");
        String userPass = request.getParameter("userpass");
        System.out.println("轉碼前:" + userName + "---" + userPass);

        // GET 請求的中文亂碼處理
        userName = new String(userName.getBytes("ISO8859-1"), "UTF-8");
        userPass = new String(userPass.getBytes("ISO8859-1"), "UTF-8");
        System.out.println("轉碼後:" + userName + "---" + userPass);

        if ("陳紅軍".equals(userName) && "123".equals(userPass)) {
            response.getOutputStream().write("登錄成功".getBytes());
        } else {
            response.getOutputStream().write("登錄失敗".getBytes());
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

web.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
    https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>video</display-name>

    <servlet>
        <display-name>LoginServlet</display-name>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>www.csdn.net.servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
</web-app>

關於 GET 亂碼那兩行:Tomcat 默認用 ISO8859-1 解碼 GET 參數,所以要在服務端手動轉回 UTF-8。POST 則可以通過 request.setCharacterEncoding("UTF-8") 解決,或者改 Tomcat 的 server.xml 加 URIEncoding="UTF-8"。

六、新手常見的四個 Bug

Bug 1:忘記加網絡權限。

<!-- 必須加在 manifest 裡 -->
<uses-permission android:name="android.permission.INTERNET"/>

缺了它,請求會靜默失敗或直接拋異常,LogCat 裡能看到相關提示。

Bug 2:在主線程發網絡請求。如果在 onClick 裡直接調 loginByGet(userName, userPass) 而不開子線程,會拋 NetworkOnMainThreadException。Android 4.0 之後 StrictMode 默認開啟了對主線程網絡的檢測,這是硬性限制,不是警告。

Bug 3:把服務器地址寫成本機地址。寫成 https://localhost:8080/... 或 https://127.0.0.1:8080/... 時,這個「本機」指的是模擬器或手機自己,而不是你電腦上的 Tomcat。正確做法是用開發機在局域網中的 IP(如示例的 172.16.237.200)。如果用的是 AVD 模擬器,也可以用 10.0.2.2 這個特殊地址訪問宿主機。

Bug 4:忘記在 finally 中 disconnect。示例裡我把 urlConnection 提到 try 外面並在 finally 中釋放,養成習慣能避免連接洩漏。

留個思考題

目前響應內容只是 System.out.println 打印出來了。試著把它顯示到界面上——比如登錄成功後跳到主界面,失敗時用 Toast 提示。

提示:子線程不能直接更新 UI,需要通過 runOnUiThread()、Handler 或 AsyncTask 把結果拋回主線程。這是下一個必學的知識點。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved