Android 採用HttpClient提交資料到伺服器,androidhttpclient
在前幾篇文章中《Android 採用get方式提交資料到伺服器》《Android 採用post方式提交資料到伺服器》介紹了android的兩種提交資料到伺服器的方法
本文繼續介紹採用HttpClient提交資料到伺服器
HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程式需要直接通過 HTTP 協議來訪問網路資源。雖然在 JDK 的 java net包中已經提供了訪問 HTTP 協議的準系統,但是對於大部分應用程式來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支援 HTTP 協議的用戶端編程工具包,並且它支援 HTTP 協議最新的版本和建議。HttpClient 已經應用在很多的項目中,比如 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。
修改代碼如下:
public void LoginHttpClientGet(View view) { String name = et_name.getText().toString().trim(); String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) { Toast.makeText(this, "使用者名稱密碼不可為空", 0).show(); } else { // 1、開啟一個瀏覽器 HttpClient client = new DefaultHttpClient(); // 2、輸入地址 String path = "http://169.254.168.71:8080/web/LoginServlet?username=" + name + "&password=" + pwd; try { HttpGet httpGet = new HttpGet(path); // 3、敲斷行符號 HttpResponse response = client.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); // 把is的內容轉換為字串 ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } String result = new String(bos.toByteArray()); is.close(); Toast.makeText(this, result, 0).show(); } else { Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "請求失敗,請檢查logcat日誌控制台", 0).show(); } } } public void LoginHttpClientPost(View view) { String name = et_name.getText().toString().trim(); String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) { Toast.makeText(this, "使用者名稱密碼不可為空", 0).show(); } else { // 1、開啟一個瀏覽器 HttpClient client = new DefaultHttpClient(); // 2、輸入地址 String path = "http://169.254.168.71:8080/web/LoginServlet?username=" + name + "&password=" + pwd; try { HttpPost httpPost = new HttpPost(path); //指定要去提交的資料實體 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("username", name)); parameters.add(new BasicNameValuePair("password", pwd)); httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); //3、敲斷行符號 HttpResponse response = client.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); // 把is的內容轉換為字串 ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } String result = new String(bos.toByteArray()); is.close(); Toast.makeText(this, result, 0).show(); } else { Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "請求失敗,請檢查logcat日誌控制台", 0).show(); } } }