04_android入門_採用HttpURLConnection的GET方式實現登陸案例

來源:互聯網
上載者:User

1.概述

每個 HttpURLConnection 執行個體都可用於產生單個請求,但是其他執行個體可以透明地共用串連到 HTTP 伺服器的基礎網路。請求後在 HttpURLConnection 的 InputStream 或 OutputStream 上調用 close() 方法可以釋放與此執行個體關聯的網路資源,但對共用的持久串連沒有任何影響。如果在調用 disconnect() 時持久串連空閑,則可能關閉基礎通訊端。

2.在03_android入門_採用RelativeLayout實現登陸介面效果的案例繼續完善 效果如下:


點擊登陸按鈕 在伺服器的控制台看到的結果<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PGltZyBzcmM9"http://www.2cto.com/uploadfile/Collfiles/20140523/2014052309114461.jpg" alt="\">

在點擊登陸按鈕之前,先通過eclipse中所帶的LogCat的工具,點擊


+號 彈出對話方塊


添加過濾的名稱和過濾的標識 點擊ok完成。

當點擊登陸按鈕之後即可在LogCat中看到執行的結果


當你輸入錯誤的使用者名稱和密碼的時候你可以看到如下效果


3.具體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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 設定顯示的視圖setContentView(R.layout.activity_login);// 通過 findViewById(id)方法擷取使用者名稱的控制項對象et_name = (EditText) findViewById(R.id.et_name);// 通過 findViewById(id)方法擷取使用者密碼的控制項對象et_pass = (EditText) findViewById(R.id.et_pass);}/** * 通過android:onClick="login"指定的方法 , 要求這個方法中接受你點擊控制項對象的參數v *  * @param v */public void login(View v) {// 擷取點擊控制項的idint id = v.getId();// 根據id進行判斷進行怎麼樣的處理switch (id) {// 登陸事件的處理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("----------------------發送請求到伺服器----------------------");// 訪問網路 (需要一個網路的許可權) // 訪問網路(耗時的操作) 避免阻塞主線程(UI) 需要開啟新的子線程來處理new Thread() {public void run() {// 調用loginByGet方法loginByGet(userName, userPass);};}.start();}break;default:break;}}/** * 通過GET方式發送的請求 *  * @param userName * @param userPass */public void loginByGet(String userName, String userPass) {try {// 佈建要求的地址 通過URLEncoder.encode(String s, String enc)// 使用指定的編碼機制將字串轉換為 application/x-www-form-urlencoded 格式String spec = "http://172.16.237.200:8080/video/login.do?username="+ URLEncoder.encode(userName, "UTF-8") + "&userpass="+ URLEncoder.encode(userPass, "UTF-8");// 根據地址建立URL對象(網路訪問的url)URL url = new URL(spec);// url.openConnection()開啟網路連結HttpURLConnection 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");// 擷取響應的狀態代碼 404 200 505 302if (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對象中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();}}}

4.項目資訊清單檔(AndroidManifest.xml)

                                                                                            

5.關於伺服器中我僅寫一個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檔案的配置是:

  video            LoginServlet    LoginServlet    www.csdn.net.servlet.LoginServlet          LoginServlet    /login.do    

6.關於程式中學生經常出現的bug分析

6.1.忘記在項目資訊清單檔中添加訪問網路的許可權.

      
那麼程式啟動並執行時候會出現如下bug


6.2.在按鈕點擊的事件處理中直接調用

loginByGet(userName, userPass);
方法沒有在子線程中調用
loginByGet(userName, userPass);
方法 就會出現如下bug


bug說明:在android4.0以後的版本中要想發送一個網路的請求,就必須把這個請求寫在子線程中,否則就會出現如上的bug

6.3.在發送網路的請求的時候把請求的地址:

http://172.16.237.200:8080/video/login.do
寫成了

http://localhost:8080/video/login.do或者http://127.0.0.1:8080/video/login.do

就會出現如下bug:



以上理解之後請同學們思考怎麼把返回的資料寫在的位置尼



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.