編輯:關於 Android 程式設計
GET 是網路請求中最基礎的一種提交方式,它的特點是把參數直接拼接在 URL 的末尾。本文透過一個登入的範例,完整示範如何在 Android 中用 GET 提交資料並取得回應。
final String path = "https://192.168.1.103/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;
請求的程式碼與以往相同:
URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); if(conn.getResponseCode() == 200){ }
瀏覽器在發送請求攜帶資料時會自動對資料做 URL 編碼,我們寫程式時同樣需要為中文進行編碼。URLEncoder.encode(name) 這個單參數版本已經過時,推薦使用 URLEncoder.encode(name, "utf-8"),它能明確指定編碼為 utf-8;若編碼不是 utf-8,這個帶參數的版本同樣適用。
String path = "https://192.168.1.103/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
由於網路請求屬於耗時操作,必須放在子執行緒中進行,再透過 Handler 把結果回傳到主執行緒更新 UI:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { Toast.makeText(MainActivity.this, (String)msg.obj, 0).show(); } }; public void click(View v){ EditText et_name = (EditText) findViewById(R.id.et_name); EditText et_pass = (EditText) findViewById(R.id.et_pass); final String name = et_name.getText().toString(); final String pass = et_pass.getText().toString(); Thread t = new Thread(){ @Override public void run() { @SuppressWarnings("deprecation") String path = "https://192.168.13.13/Web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); if(conn.getResponseCode() == 200){ InputStream is =conn.getInputStream(); String text = Utils.getTextFromStream(is); Message msg = handler.obtainMessage(); msg.obj = text; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } }
這個方法負責把伺服器回傳的輸入流讀成字串,透過 ByteArrayOutputStream 同步累積資料,最後再轉為字串:
public static String getTextFromStream(InputStream is){ byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream( ); try { while((len = is.read(b)) != -1){ bos.write(b, 0, len); } String text = new String(bos.toByteArray( )); return text; } catch (IOException e) { e.printStackTrace(); } return null; }
掌握 GET 提交的三個要點——拼接 URL、URL 編碼、放到子執行緒並用 Handler 回傳——就能輕鬆完成最基礎的網路通訊。下一篇將進一步說明 POST 方式的實作。
Android 自定義 View 實作芝麻分趨勢折線圖
這個效果幾天前就寫完了,只是一直沒抽出時間更新部落格。原本打算把芝麻分的雷達圖也一併做完再發文,剛好今天在公眾號上看到有人分享了雷達圖的實作,那就算互補吧。平時寫的東西不
RecyclerView 使用指南:從基礎到點擊與增刪動畫
參考官方文檔:https://developer.android.com/training/material/lists-cards.html 一、為什麼有了 ListV
Android 產品研發(二十一)——UI 優化實戰
上一篇文章我們講解了 Android 產品研發過程中的代碼 Review。通過代碼 Review 能夠提高產品質量、增強團隊成員之間的溝通、提高開發效率,所以在良好的產品
OkHttp 框架入門實戰:Android 網路請求一篇搞定
自 Android 6.0 起,Google 移除了 HttpClient 相關 API,改用 HttpURLConnection 取代。在實際開發中,網路請求幾乎是每個