編輯:關於 Android 程式設計
客戶端與服務端通信幾乎是每個 App 的必備能力。HTTP 協議中,GET 是最基礎的請求方式之一,常用於向服務端查詢數據。本文將以一個登陸功能為例,完整示範如何從 Android 端用 GET 方式向 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>
由於 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 方式。
Android 仿微信錄製音頻並發送的完整實現
MyRecorder(仿微信,錄製音頻並發送功能)① 布局實現(activity_main.xml)整體採用線性布局,上方是一個 ListView,下方是一個自定義 Bu
Android 學習筆記(36):兩種事件處理機制詳解
在 Android 中,事件處理主要分為兩大類:基於回調(callback)的事件處理,以及基於監聽(listener)的事件處理。兩者各有適用場景,理解其差異是打好 U
AXML 解析:看懂 Android 二進位 XML 檔案格式
簡述 AXML 即 Android Binary XML,是 Android 應用程式 APK 中儲存 XML 資料的一種方式。它能夠縮小 XML 檔案的體積,也方便系統
Android ListView 分頁載入資料實作教學
當 ListView 需要顯示大量資料時,一次載入全部內容往往不是最好的做法。分頁載入可以讓使用者逐步瀏覽資料,也能改善整體使用體驗。本文示範如何在 ListView 底