1. 程式人生 > >Android傳統HTTP請求get----post方式提交資料(包含亂碼問題)

Android傳統HTTP請求get----post方式提交資料(包含亂碼問題)

1.模仿登入頁面顯示(使用傳統方式是面向過程的)

使用Apache公司提供的HttpClient  API是面向物件的

(文章底部含有原始碼的連線,包含了使用async框架)

(解決中文亂碼的問題,主要是對中文的資料進行URL編碼)

android手機預設的編碼是UTF-8

2.手機截圖Demo

3.伺服器截圖

程式碼如下:

伺服器端的程式碼:

//測試 android裝置登入
public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//對資料進行編碼,解決亂碼問題
		username  = new String(username.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println("username--:"+username+"---password:"+password);
		
		if(username.equals("admin") && password.equals("123")){
			response.getOutputStream().write("登入成功".getBytes("UTF-8"));
		}else{
			response.getOutputStream().write("登入失敗".getBytes("UTF-8"));
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		request.setCharacterEncoding("UTF-8");
		doGet(request, response);

	}

}

Android客戶端

佈局檔案的部分:

//測試 android裝置登入
public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//對資料進行編碼,解決亂碼問題
		username  = new String(username.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println("username--:"+username+"---password:"+password);
		
		if(username.equals("admin") && password.equals("123")){
			response.getOutputStream().write("登入成功".getBytes("UTF-8"));
		}else{
			response.getOutputStream().write("登入失敗".getBytes("UTF-8"));
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		request.setCharacterEncoding("UTF-8");
		doGet(request, response);

	}

}

Activity程式碼部分:

(注意:android4.0之後訪問網路必須開子執行緒進行訪問,並且涉及到許可權,記得加上訪問網路的許可權

下面的程式碼中,我寫入get和post兩種方式的執行緒請求。。。。。。。。。。。。。慢慢體會

public class MainActivity extends AppCompatActivity {
    private static final int SUCCESS = 0;
    private static final int FAILE = 1;
    private static final int NET_ERROR = 3;
    private static final String TAG = "MainActivity";
    EditText et_username;
    EditText et_password;
    TextView show_result;
    String username;
    String password;

    final String path = "http://188.188.7.85/Android_Server/Login";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;

            switch (what) {
                case SUCCESS:
                    String data = (String) msg.obj;
                    show_result.setText(data);
                    break;
                case FAILE:
                    Toast.makeText(MainActivity.this, "連線伺服器失敗", Toast.LENGTH_SHORT).show();
                    break;
                case NET_ERROR:
                    Toast.makeText(MainActivity.this, "網路出現異常", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

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

        username = et_username.getText().toString().trim();
        password = et_password.getText().toString().trim();
    }

    public void login(View view) {
        username = et_username.getText().toString().trim();
        password = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "使用者名稱和密碼不能為空", Toast.LENGTH_SHORT).show();
            return;
        }

        //使用傳統get方式的請求伺服器
//        new Thread_get().start();


        //使用傳統的post方式請求伺服器
        new Thread_post().start();

    }

    //傳統的post方式請求伺服器端
    class Thread_post extends Thread {
        @Override
        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                //1.設定請求方式
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(5000); //設定連線的超時事件是5秒

                //2.組合資料,一定要將資料進行URL編碼
                String commitData = "username="+URLEncoder.encode(username,"UTF-8")+"&password="+URLEncoder.encode(password,"UTF-8");

                // 3. 指定content-type -實際上就是指定傳輸的資料型別
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


                //4.指定content-length Content-Length: 資料的長度
                conn.setRequestProperty("Content-Length", commitData.length() + "");

                //5.開啟輸出流,告訴伺服器,我要寫資料了
                conn.setDoOutput(true);


                //6.開始寫資料
                OutputStream os = conn.getOutputStream();
                os.write(commitData.getBytes());
//                os.close();

                int code = conn.getResponseCode();  //獲取返回的成功程式碼
                Log.i(TAG, "code:---" + code);

                if (code == 200) {
                    //表示連線伺服器成功返回資訊
                    String data = ServerTools.getInfo(conn.getInputStream());

                    Log.i(TAG, "data:---" + data);
                    //使用訊息處理機制,將資料傳遞給主執行緒
                    Message ms = new Message();
                    ms.what = SUCCESS;
                    ms.obj = data;
                    handler.sendMessage(ms);
                } else {
                    //使用訊息處理機制,將資料傳遞給主執行緒
                    Message ms = new Message();
                    ms.what = FAILE;
                    handler.sendMessage(ms);
                }

            } catch (Exception e) {

                //使用訊息處理機制,將資料傳遞給主執行緒
                Message ms = new Message();
                ms.what = NET_ERROR;
                handler.sendMessage(ms);
                e.printStackTrace();
            }
        }
    }

    //傳統的get方式請求伺服器端
    class Thread_get extends Thread {
        @Override
        public void run() {
            try {
                String getPath = path +
                        "?username=" + URLEncoder.encode(username, "UTF-8") +
                        "&password=" + URLEncoder.encode(password, "UTF-8");
                URL url = new URL(getPath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000); //設定連線的超時事件是5秒
                int code = conn.getResponseCode();  //獲取返回的成功程式碼

                Log.i(TAG, "code:---" + code);
                ;

                if (code == 200) {
                    //表示連線伺服器成功返回資訊
                    String data = ServerTools.getInfo(conn.getInputStream());

                    Log.i(TAG, "data:---" + data);
                    //使用訊息處理機制,將資料傳遞給主執行緒
                    Message ms = new Message();
                    ms.what = SUCCESS;
                    ms.obj = data;
                    handler.sendMessage(ms);
                } else {
                    //使用訊息處理機制,將資料傳遞給主執行緒
                    Message ms = new Message();
                    ms.what = FAILE;
                    handler.sendMessage(ms);
                }

            } catch (Exception e) {

                //使用訊息處理機制,將資料傳遞給主執行緒
                Message ms = new Message();
                ms.what = NET_ERROR;
                handler.sendMessage(ms);
                e.printStackTrace();
            }
        }
    }

}


工具類:

public class ServerTools {

    //從服務端獲取流資料進行轉化成文字檔案
    public static String getInfo(InputStream in) {

        //將資料流寫在記憶體中
        ByteArrayOutputStream raf = new ByteArrayOutputStream();
        String data = null;

        try{
            byte[] bt = new byte[1024];
            int len =0 ;
            while((len = in.read(bt)) != -1){
                raf.write(bt,0,len);
            }

           data = raf.toString();
        }catch (Exception e){
            e.printStackTrace();
        }

        return data;
    }
}



Android的原始碼已經放在github中: