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

Android 使用 GET 方式向服務器請求與提交數據全攻略

編輯:關於 Android 程式設計

客戶端與服務端通信幾乎是每個 App 的必備能力。HTTP 協議中,GET 是最基礎的請求方式之一,常用於向服務端查詢數據。本文將以一個登陸功能為例,完整示範如何從 Android 端用 GET 方式向 Servlet 後端發送請求並解析響應。

第一步:搭建處理登陸請求的 Servlet

後端使用 Java Servlet 接收請求,通過 getParameter 獲取用戶名與密碼,校驗成功後返回對應結果。

package com.wzw.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 password = request.getParameter("password");
        if (username.equals("admin") && password.equals("123456")) {
            response.getWriter().println("success");
        } else {
            response.getWriter().println("failed");
        }
    }
}

第二步:編寫界面布局

布局很簡單:兩個輸入框分別填寫用戶名和密碼,一個按鈕觸發 GET 提交。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" tools:context=".MainActivity" >
    <EditText android:layout_marginTop="10dp" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/et_username" android:hint="請輸入名字"/>
    <EditText android:layout_marginTop="10dp" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/et_password" android:hint="請輸入密碼"/>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:onClick="doGet" android:text="GET方式提交"/>
</LinearLayout>

第三步:在 Activity 中實現請求邏輯

由於 Android 4.0 之後禁止在主線程進行網絡操作,我們需要開啟子線程發起請求,並用 runOnUiThread 回到主線程彈出結果提示。

public class MainActivity extends Activity {
    private EditText etUsername;
    private EditText etPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etUsername = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
    }

    public void doGet(View v) {
        final String username = etUsername.getText().toString();
        final String password = etPassword.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 訪問網絡要在子線程中實現
                final String state = NetUtil.loginOfGet(username, password);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this, state, 0).show();
                    }
                });
            }
        }).start();
    }
}

第四步:封裝網絡工具類

把 GET 請求的細節抽到一個工具類中,讓代碼更清晰、易於復用。

package com.wzw.submitdata.utils;

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

public class NetUtil {
    /** 使用 GET 訪問網絡 */
    public static String loginOfGet(String username, String password) {
        HttpURLConnection conn = null;
        try {
            String data = "username=" + username + "&password=" + password;
            URL url = new URL("https://192.168.1.4:8080/AndroidServer/LoginServlet?" + data);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(5000);
            conn.connect();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                return getStringFromInputStream(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) { conn.disconnect(); }
        }
        return null;
    }

    /** 根據輸入流返回字符串 */
    private static String getStringFromInputStream(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = is.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        is.close();
        String html = baos.toString();
        baos.close();
        return html;
    }
}

這樣,Android 端就能成功向服務器發起 GET 請求並拿到響應了。GET 的特點是把參數拼接到 URL 後面,適合傳輸少量、非敏感數據;如果需要提交大量或敏感信息,則應改用 POST 方式。

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