1. 程式人生 > >http協議從客戶端提交資料給伺服器並返回資料

http協議從客戶端提交資料給伺服器並返回資料

老羅視訊學習。

本例從客戶端提交資料給伺服器,伺服器接收到資料之後,看是否匹配,匹配返回字串“login is success!”,失敗返回“login is error!”

一.客戶端。

初始化url地址

private static String path = "http://192.168.10.102:8080/myhttp/servlet/LoginActivity";
	private static URL url;
	
	static{
		
		try {
			url = new URL(path);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


setPostMessage函式

getOutputStream是向伺服器傳遞資料用的。

getInputStream是從伺服器獲取資料用的。

向伺服器輸入資料傳遞圖片之類的,要用HttpUrlConnection類

doInput預設值是true,doOutput預設值是false。

private static String sendPostMessage(Map<String, String> params,String encode) {
		//請求體封裝在StringBuffer中
		StringBuffer buffer = new StringBuffer();
		//buffer.append("?");
		try {
			
			
			//判斷是否為空
			if(params!=null && !params.isEmpty()){
				//迭代for迴圈
				
				for(Map.Entry<String, String> entry : params.entrySet()){
					//append,追加字串
					buffer.append(entry.getKey())
					.append("=")
					.append(URLEncoder.encode(entry.getValue(),encode))
					.append("&");
				}
				
			}
			//刪掉最後多餘的那個“&”
			buffer.deleteCharAt(buffer.length()-1);
			System.out.print(buffer.toString());
			
			
			//接下來是http協議內容
			//開啟連結
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			//設定伺服器斷開重連時間
			urlConnection.setConnectTimeout(3000);
			//設定提交方式
			urlConnection.setRequestMethod("POST");
			//設定從伺服器讀取資料
			urlConnection.setDoInput(true);
			//設定向伺服器寫資料
			urlConnection.setDoOutput(true);
			//接下來需要把url的請求的內容,封裝到一個請求體中
			//獲得上傳資訊的位元組大小
			byte[] data = buffer.toString().getBytes();
			//設定請求體的型別
			//設定請求體型別為文字型別,暫時不涉及圖片及二進位制資料
			urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//設定請求體的長度
			urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
			
			//獲得輸出流,向伺服器輸出資料
			OutputStream outputStream = urlConnection.getOutputStream();
			outputStream.write(data,0,data.length);
			outputStream.close();
			//獲得伺服器響應的結果和狀態碼
			int responseCode = urlConnection.getResponseCode();
			if (responseCode == 200) {
				//把inputStream改為String傳遞出來
				return ChangeInputStream(urlConnection.getInputStream(),encode);
			}
		}catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return path;
		
	}


changeInputStream函式如下:

把InputStream以encode格式轉換為String

private static String ChangeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String resultString = "";
		if(inputStream!=null) {
			try {
				//資料迴圈儲存在outputStream中
				while ((len=inputStream.read(data))!=-1) {
					outputStream.write(data,0,len);
				}
				//首先轉換為位元組陣列,然後以encode編碼格式轉換為字串
				resultString = new String(outputStream.toByteArray(),encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return resultString;
	}

測試main函式如下:
	public static void main(String[] args) {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "123");
		
		String encode = "utf-8";
	
		String resString = HttpUrils.sendPostMessage(params, encode);
		System.out.print("------>"+resString);
	}


二.伺服器端,還用get方式例子裡用到的伺服器。

LoginActivity繼承自HttpServlet

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//設定編碼格式
		resp.setContentType("text/html;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		//獲取使用者名稱username,密碼password
		PrintWriter out = resp.getWriter();
		String usernameString = req.getParameter("username");
		String pswdString = req.getParameter("password");
		System.out.print(usernameString);
		System.out.print(pswdString);
		//匹配成功
		if(usernameString.equals("admin")&&pswdString.equals("123")){
			out.print("login is success!");
		}//匹配不成功
		else {
			out.print("login is error!");
		}
		out.flush();
		out.close();