Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習(50):使用 POST 方式提交資料到伺服器

編輯:關於 Android 程式設計

相較於把參數暴露在 URL 上的 GET,POST 透過請求流把資料寫給伺服器,更適合傳送敏感或較長的內容。本文延續上一篇的登入範例,說明 POST 的實作要點。

POST 的核心要點

POST 提交資料是把資料以串流方式寫給伺服器,並在協議標頭中多出兩個屬性:

Content-Type: application/x-www-form-urlencoded,用來描述提交資料的 mimetype。

Content-Length: 30,用來描述提交資料的長度。

//給請求頭添加post多出來的兩個屬性 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + "");

接著要允許打開 POST 請求的輸出流:

conn.setDoOutput(true);

最後取得連線的輸出流,把要提交的資料寫進去:

OutputStream os = conn.getOutputStream(); os.write(data.getBytes());

核心程式碼

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { Toast.makeText(MainActivity.this, (String)msg.obj, 0).show(); } }; public void click(View v){ EditText et_name = (EditText) findViewById(R.id.et_name); EditText et_pass = (EditText) findViewById(R.id.et_pass); final String name = et_name.getText().toString(); final String pass = et_pass.getText().toString(); Thread t = new Thread(){ @Override public void run() { @SuppressWarnings("deprecation") String path = "https://192.168.13.13/Web2/servlet/LoginServlet"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //拼接出要提交的數據的字符串 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; //添加post請求的兩行屬性 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + ""); //設置打開輸出流 conn.setDoOutput(true); //拿到輸出流 OutputStream os = conn.getOutputStream(); //使用輸出流往服務器提交數據 os.write(data.getBytes()); if(conn.getResponseCode() == 200){ InputStream is = conn.getInputStream(); String text = Utils.getTextFromStream(is); Message msg = handler.obtainMessage(); msg.obj = text; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } }

讀取串流的工具方法 getTextFromStream

 public static String getTextFromStream(InputStream is){ byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { while((len = is.read(b)) != -1){ bos.write(b, 0, len); } String text = new String(bos.toByteArray()); return text; } catch (IOException e) { e.printStackTrace(); } return null; }

對比 GET 與 POST 可以發現,兩者的差異主要在於資料傳遞的方式:GET 把參數拼在 URL 上,POST 則透過輸出流把資料寫給伺服器,並需要額外設定 Content-Type 與 Content-Length 兩個標頭,同時別忘了呼叫 setDoOutput(true) 開啟輸出流。掌握這些差異,就能依場景靈活選擇合適的提交方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved