編輯:關於Android編程
向服務器提交數據有兩種方式,post和get。兩者的區別主要有三點,安全性、長度限制、數據結構。其中get請求安全性相比較而言較差,數據長度受浏覽器地址欄限制,沒有方法體。兩種都是較為重要的數據提交方式。現簡單介紹一下三種post和get的提交方式。無論是哪種方法實現post和get,get 的訪問路徑都要攜帶數據,而post提交是把數據放在方法體中。
普通方法實現get/post提交:
嚴格遵照Http協議進行數據傳輸。在安卓開發環境下,由於主線程不能進行網絡訪問,因此需要在開啟一個子線程向服務器提交數據。為了更加直觀的觀察數據,可以在程序屏幕上顯示服務器反饋信息。又由於子線程無法更改UI界面,因此需要引入Hnndler代理器。實現get/post提交基本步驟就是,獲取URL路徑,根據路徑得到Http連接,用HttpURLConnection對象設置相關的http配置信息、提交方式以及獲取反饋碼。當響應碼為200時表示提交成功,可以通過HttpURLConnection以流的形式獲取反饋信息。
普通GRT提交方式:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq + "&pwd=" + pwd; new Thread() { public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); String result = StreamTools.ReadStream(is); Message msg = Message.obtain(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = ERROR1; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Message msg = Message.obtain(); msg.what = ERROR2; handler.sendMessage(msg); } } }.start(); }
普通POST提交方式:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload"; new Thread() { public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("POST"); conn.setReadTimeout(5000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String data = "qq="+URLEncoder.encode(qq,"utf-8")+"&pwd=" + URLEncoder.encode(pwd,"utf-8"); conn.setRequestProperty("Content-Length",String.valueOf(data.length())); conn.setDoOutput(true); conn.getOutputStream().write(data.getBytes()); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); String result = StreamTools.ReadStream(is); Message msg = Message.obtain(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = ERROR1; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Message msg = Message.obtain(); msg.what = ERROR2; handler.sendMessage(msg); } } }.start(); }
用httpclien實現get/post提交的只需要一下幾個步驟:
1.創建HttpClient對象,實現打開浏覽器的功能
HttpClient client = new DefaultHttpClient();
2.輸入地址或者數據 ,用到HttpGet()或HttpPost(),傳入要訪問的路徑,得到HttpGet或HttpPost對象。
HttpGet httpGet = new HttpGet(path);
3.把獲得的HttpGet或HttpPost對象發送到服務器,實現敲回車的功能,得到HttpResponse對象。
HttpResponse response = client.execute(httpGet);
4.得到HttpResponse對象獲取狀態行中的狀態碼,判斷狀態碼狀態碼。
int code = response.getStatusLine().getStatusCode();
5.同樣用HttpResponse對象獲取相應內容,存入流對象。最後將得到的流對象轉為字符串進行顯示。
InputStream is = response.getEntity().getContent();
其中要注意的一點是用post請求時要傳遞值所以要多出一個步驟。具體而言,先創建一個list集合,集合的泛型用NameValuePair表示,類似於鍵值對的形式存儲要傳遞的數據。接著向集合中添加要提交數據。最後用HttpPost對象把集合存入請求體中。
用HttpClient實現GET提交:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq + "&pwd=" + pwd; new Thread() { public void run() { try { HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(path); HttpResponse response = client.execute(httpget); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); String result = StreamTools.ReadStream(is); Message msg = Message.obtain(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = ERROR1; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Message msg = Message.obtain(); msg.what = ERROR2; handler.sendMessage(msg); } } }.start(); }
用HttpClient實現POST提交:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload"; new Thread() { public void run() { try { HttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(path); List<NameValuePair> parameter = new ArrayList(); parameter.add(new BasicNameValuePair("qq", qq)); parameter.add(new BasicNameValuePair("pwd", pwd)); httppost.setEntity(new UrlEncodedFormEntity(parameter,"utf-8")); HttpResponse response = client.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); String result = StreamTools.ReadStream(is); Message msg = Message.obtain(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = ERROR1; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Message msg = Message.obtain(); msg.what = ERROR2; handler.sendMessage(msg); } } }.start(); }
使用開源框架實現get/post提交:
利用框架實現get/post提交不需要再開啟子線程。直接在主線程進行get/post的提交,大大的減少了工作量。但操作前需要導包。然後直接創建一個AsyncHttpClient對象,用AsyncHttpClient對象的post方法和get方法,發送請求,並在AsyncHttpResponseHandler()對象中獲得相應信息。同樣若是post請求,仍舊需要傳遞值。這裡可以用RequestParams對象添加要傳遞的值。
在文件下添加jar包:
用開源框架實現GET提交:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq + "&pwd=" + pwd; AsyncHttpClient client = new AsyncHttpClient(); client.get(path, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { // TODO Auto-generated method stub tv_result.setText(new String(responseBody)); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // TODO Auto-generated method stub tv_result.setText("錯誤原因:" + new String(responseBody)); } }); }
用開源框架實現POST請求:
public void load(View view){ final String qq = et_qq.getText().toString().trim(); final String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) { Toast.makeText(MainActivity.this, "qq號或密碼為空", 0).show(); return; } final String path = "http://192.168.1.114:8080/qqload/qqload"; AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.add("qq", qq); params.add("pwd", pwd); client.post(path,params,new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { // TODO Auto-generated method stub tv_result.setText(new String(responseBody)); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // TODO Auto-generated method stub tv_result.setText(new String(responseBody)); } }); }
通過以上任何一種方式可以實現的功能是,從安卓手機端提交數據到服務器端,服務器端進行判斷,並返回相應的結果。三種方式各有利弊,實現效果相同,在實際的使用過程中可以根據本身的需要進行選擇。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持本站!
android的開發模式,也就是項目最基本的構建模式,也不是說需要固定不變的模式,在項目中可以靈活運用。而MVP開發模式屬於MVC的變種升級,其相對於mvc模式來說,更高
想要學好安卓開發,就必須理解安卓軟件的生命周期,明白一個活動的創建、啟動、停止、暫停、重啟和銷毀的過程,知道各個階段會調用什麼函數進行處理不同的情況,這裡我們就來說說A
在Android開發和調試的過程中,Log的使用是非常頻繁的,一個好的Log工具可以幫你節省很多時間,所以凱子哥抽空寫了個這個開源項目KLog,希望可以幫助大家提高開發
微信對話列表滑動刪除效果很不錯的,借鑒了github上SwipeListView(項目地址:https://github.com/likebamboo/SwipeList