標籤:put client utils orm tps and 資料流 new void
1.模仿登入頁面顯示(使用傳統方式是面向過程的)
使用Apache公司提供的HttpClient API是物件導向的
(文章底部含有源碼的串連,包括了使用async架構)
(解決中文亂碼的問題。主要是對中文的資料進行URL編碼)
android手機預設的編碼是UTF-8
2.手機Demo
3.server
代碼例如以下:
server端的代碼:
//測試 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);}}
Androidclient
布局檔案的部分:
//測試 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, "串連server失敗", 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, "username與password不可為空", Toast.LENGTH_SHORT).show(); return; } //使用傳統get方式的請求server// new Thread_get().start(); //使用傳統的post方式請求server new Thread_post().start(); } //傳統的post方式請求server端 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.開啟輸出資料流。告訴server,我要寫資料了 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) { //表示串連server成功返回資訊 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方式請求server端 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) { //表示串連server成功返回資訊 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中:
傳統方式Demo地址:https://github.com/momxmo/HTTP_get_post
Apache提供的HttpClient API物件導向的方式Demo:https://github.com/momxmo/HttpClient_get_post
使用async-http-master流行架構進行http請求:https://github.com/momxmo/Http_android-async-http-master_Demo
????
Android傳統HTTP請求get----post方式提交資料(包括亂碼問題)