Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android編程入門 >> Android面向HTTP協議發送post請求

Android面向HTTP協議發送post請求

編輯:Android編程入門

/**
	 * 採用post請求的方式
	 * 
	 * @param username
	 * @param password
	 * @return null表示求得的路徑有問題,text返回請求得到的數據
	 */
	public static String postRequest(String username, String password) {
		try {
			String path = "http://172.22.64.156:8080/0001AndroidWebService/LoginServlet";
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(500);
			conn.setRequestMethod("POST");
			// username=donghongyu&&password=123
			// 准備要傳輸的數據
			String data = "username=" + URLEncoder.encode(username)
					+ "&password=" + URLEncoder.encode(password);
			// 設置請求的內容的類型
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", data.length() + "");

			// 開啟向server寫入的權限
			conn.setDefaultUseCaches(true);
			// 獲取http連接的輸出流
			OutputStream os = conn.getOutputStream();
			// 向server寫入數據
			os.write(data.getBytes());

			int code = conn.getResponseCode();
			if (code == 200) {
				// 請求成功
				InputStream is = conn.getInputStream();
				String text = StreamUtil.readStream(is);
				return text;
			} else {
				// 請求失敗
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

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