Android客戶端通過GET和POST向服務器發送數據

在進行開發之前,需要先了解HTTP協議及網絡編程方面的知識。

Android

1.業務層類,通過使用android內置HttpClient發送GET、POST請求

       /**
	 * 通過HttpClient發送Post請求
	 * @param path 請求路徑
	 * @param params 請求參數
	 * @param ecoding 請求編碼
	 * @return 請求是否成功
	 */
	private static boolean sendHttpClientPOSTRequest(String path,
			Map<String, String> params, String ecoding) throws Exception {
		List<NameValuePair> pair=new ArrayList<NameValuePair>();//存放請求參數
		if(params!=null && !params.isEmpty()){
			for (Map.Entry<String, String> entry : params.entrySet()) {
				pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
			}
		}
		UrlEncodedFormEntity enFormEntity=new UrlEncodedFormEntity(pair,ecoding);
		HttpPost httpPost=new HttpPost(path);
		httpPost.setEntity(enFormEntity);
		DefaultHttpClient client=new DefaultHttpClient();
		HttpResponse response=client.execute(httpPost);
		if(response.getStatusLine().getStatusCode()==200){
			return true;
		}
		return false;
	}
	
	/**
	 * 通過HttpClient發送GET請求
	 * @param path 請求路徑
	 * @param params 請求參數
	 * @param ecoding 請求編碼
	 * @return 請求是否成功
	 */
	private static boolean sendHttpClientGETRequest(String path,
			Map<String, String> params, String ecoding) throws Exception {
		StringBuilder url=new StringBuilder(path);
		url.append("?");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			url.append(entry.getKey()).append("=");
			url.append(URLEncoder.encode(entry.getValue(),ecoding));
			url.append("&");
		}
		url.deleteCharAt(url.length()-1);
		HttpGet httpGet=new HttpGet(url.toString());
		DefaultHttpClient client=new DefaultHttpClient();
		HttpResponse response=client.execute(httpGet);
		if(response.getStatusLine().getStatusCode()==200){
			//接收返回的響應結果,也可以不接收
			HttpEntity entity=response.getEntity();
			EntityUtils.toString(entity,ecoding);//對響應結果進行編碼
			return true;
		}
		return false;
	}
2.通過HTTP協議手動方式進行發送GET、POST請求

       /**
	 * 發送POST請求
	 * @param path 請求路徑
	 * @param params 請求參數
	 * @param ecoding 請求編碼
	 * @return 請求是否成功
	 */
	private static boolean sendPOSTRequest(String path,
			Map<String, String> params, String ecoding) throws Exception {
		//title=kaka&timelength=10
		//組拼實體數據
		StringBuilder data=new StringBuilder();
		if(params!=null && !params.isEmpty()){
			for (Map.Entry<String, String> entry : params.entrySet()) {
				data.append(entry.getKey()).append("=");
				data.append(URLEncoder.encode(entry.getValue(),ecoding));
				data.append("&");
			}
			data.deleteCharAt(data.length()-1);
		}
		byte[] entity=data.toString().getBytes();//得到實體數據
		HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);//設置允許對外輸出數據
		//設置頭字段
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		OutputStream outStream=conn.getOutputStream();
		outStream.write(entity);
		if(conn.getResponseCode()==200){
			return true;
		}
		return false;
	}

	/**
	 * 發送GET請求
	 * @param path 請求路徑
	 * @param params 請求參數
	 * @param ecoding 請求編碼
	 * @return 請求是否成功
	 */
	private static boolean sendGETRequest(String path,Map<String, String> params,String ecoding) throws Exception {
		StringBuilder url=new StringBuilder(path);
		url.append("?");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			url.append(entry.getKey()).append("=");
			url.append(URLEncoder.encode(entry.getValue(),ecoding));
			url.append("&");
		}
		url.deleteCharAt(url.length()-1);
		HttpURLConnection conn=(HttpURLConnection)new URL(url.toString()).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode()==200){
			return true;
		}
		return false;
	}
3.調用示例

       /**
	 * 調用示例保存數據
	 * @param title 標題
	 * @param length 時長
	 * @return
	 */
	public static boolean save(String title, String length) {
		String path="http://192.168.1.111:8080/ManageServlet";//服務器路徑
		Map<String, String> params=new HashMap<String, String>();
		params.put("title", title);
		params.put("timelength", length);
		try {
			return sendHttpClientGETRequest(path,params,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
源碼下載地址:Android客戶端通過GET和POST向服務器發送數據源碼


發佈了50 篇原創文章 · 獲贊 11 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章