Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> [Android學習]http協議編程的三種方式

[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 =
	// "http://192.168.137.103:8080/MyHttp/servlet/LoginAction";
	public static final String path = "http://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包:
Apache編程時用到的JAR包: 點擊打開鏈接

XMLPull解析時用到的JAR包: 點擊打開鏈接


 
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved