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

Android 學習:HTTP 協議編程的三種方式

編輯:關於 Android 程式設計

一、POST 與 GET 的區別

1、GET 是從伺服器獲取資料,POST 是向伺服器傳送資料。

2、在客戶端,GET 方式透過 URL 提交資料,資料在 URL 中可以看到;POST 方式則把資料放在 HTML HEADER 內提交。

3、對於 GET 方式,伺服器端用 Request.QueryString 獲取變數的值;對於 POST 方式,伺服器端用 Request.Form 獲取提交的資料。

4、GET 方式提交的資料最多只能有 1024 位元組,而 POST 則沒有此限制。

5、安全性問題。正如第 2 點所述,使用 GET 時參數會顯示在網址列上,而 POST 不會。所以,如果資料是中文且屬於非敏感資料,可以使用 GET;如果使用者輸入的資料不是中文字元且包含敏感內容,那麼還是使用 POST 為宜。

二、Java 中的 HTTP 編程主要有兩種

1、標準的 Java 介面

2、標準的 Apache 介面

三、標準的 Java 介面編程

1、GET 方式

 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class http_get1 { // public static final String path = // "https://192.168.137.103:8080/MyHttp/servlet/LoginAction"; public static final String path = "https://localhost:8080/MyHttp/servlet/LoginAction"; public static String getStringFromStream(InputStream is) { String str = ""; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = 0; byte[] data = new byte[1024]; if(is!=null){ try { while ((len = is.read(data)) != -1) { bos.write(data, 0, len); } str = new String(bos.toByteArray(), "utf-8"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return str; } public static InputStream useGetMethod(Map map, String encode) { InputStream is = null; StringBuffer sb = new StringBuffer(path); sb.append("?"); if (map != null && !map.isEmpty()) { for (Map.Entry entry : map.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()) .append("&"); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); URL url = null; OutputStream os = null; try { url = new URL(sb.toString()); if (url != null) { HttpURLConnection con = (HttpURLConnection) url .openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(3000); con.setDoInput(true); con.setDoOutput(true); os = con.getOutputStream(); os.write(sb.toString().getBytes(encode)); os.close(); if (con.getResponseCode() == 200) { is = con.getInputStream(); } } } catch (Exception e) { } } return is; } public static void main(String[] args) { // TODO Auto-generated method stub Map map = new HashMap(); map.put("username", "admin"); map.put("password", "1243"); String str = getStringFromStream(useGetMethod(map, "utf-8")); System.out.println(str); } }

2、POST 方式

 import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; public class http_post1 { // 使用POST請求與GET請求的區別就是POST請求不需要封裝請求路徑,只需要封裝請求參數 public static InputStream usePostMethod(Map map, String encode) { StringBuffer buffer = new StringBuffer(); InputStream is = null; OutputStream os = null; if (map != null && !map.isEmpty()) { for (Map.Entry entry : map.entrySet()) { try { buffer.append(entry.getKey()).append("=") .append(entry.getValue()) // .append(URLEncoder.encode(entry.getValue(), // encode)) .append("&"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } buffer.deleteCharAt(buffer.length() - 1); System.out.println(buffer.toString()); } try { URL url = new URL(http_get1.path); if (url != null) { HttpURLConnection con = (HttpURLConnection) url .openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setConnectTimeout(3000); byte[] tdata = buffer.toString().getBytes(); // con.setRequestProperty("Content-Type", // "application/x-www-form-urlencoded"); // con.setRequestProperty("Content-Length", // String.valueOf(tdata.length)); os = con.getOutputStream(); os.write(tdata); os.close(); if (con.getResponseCode() == 200) { is = con.getInputStream(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return is; } public static void main(String[] args) { Map map = new HashMap(); map.put("username", "admin"); map.put("password", "123"); System.out.println(http_get1.getStringFromStream(usePostMethod(map, "utf-8"))); } }

四、Apache 介面

 import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class http_myapache { public static InputStream useApacheMethod(Map map, String encode) { InputStream is = null; List list = new ArrayList(); for (Map.Entry entry : map.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { // 封裝請求參數 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode); // 設置請求參數 HttpPost post = new HttpPost(http_get1.path); post.setEntity(entity); // 執行請求 DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); // 獲取狀態碼 if (response.getStatusLine().getStatusCode() == 200) { is = response.getEntity().getContent(); } } catch (Exception e) { // TODO: handle exception } return is; } public static void main(String[] args) { Map map = new HashMap(); map.put("username", "admin"); map.put("password", "123"); System.out.println(http_get1.getStringFromStream(useApacheMethod(map, "utf-8"))); } }

總結

對於普通的 HTTP 編程,可以選擇 GET 方式或 POST 方式;但對於要求更高的 HTTP 編程場景,Apache 提供的標準介面則更加靈活。

附:Apache 編程時需要用到的 JAR 包,以及 XMLPull 解析時需要用到的 JAR 包,可參考原文提供的下載連結。

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