標籤:val tle pass ... 組合 url編碼 bytes post term
前面記錄過一篇關於http通訊,發送資料的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要記錄的是如何通過http類比表單提交資料。
一、通過GET請求方式提交:最簡單的一種方式
直接在連結後面跟上要提交的資料即可,比如: http://yychf.55555.io/get.do?username=yyc&password=yychf,通過http直接發送。然後在伺服器端可以通過request.getParameter()方法來獲得參數值。如要獲得參數username的值可以通過request.getParameter("username");
二、通過POST請求方式提交:發送更多資料
post請求方式參數比較隱蔽,資料的傳輸在請求的資料體中。一般來說,我們用POST提交表單會出現在前端html代碼中,通過submit將資料提交到表單地址中,現在需要通過純java代碼實現表單的提交。其實原理也很簡單,主要需要注意以下兩點:
- 作為表單提交資料,需要設定它的要求標頭,主要是Content-Type的值, 這裡的值是application/x-www-form-urlencoded;
- 需要將參數轉換成如key1=urlencode(value1)&key2=urlencode(value2)的形式,這裡的urlencode是指將參數值用urlencode編碼,其實就是是將表單欄位和經過編碼的欄位值經過組合以資料體的方式做了參數傳遞。
下面是具體實現代碼:
1 /** 2 * 發起http請求 3 * 發送參數(仿表單提交效果): 4 * 基本思路:1.要求標頭“Content-Type”的值為“application/x-www-form-urlencoded” 5 * 2.將參數拼接成key=value形式的字串post提交 6 * 注意:key=value中key,value即參數名、值不能有中文字元, 7 * 所以發送的資料就是key1=urlencode(value1)&key2=urlencode(value2)&...形式的字串 8 * @param urlString 9 * @param formProperties 10 * @return 11 * @throws Exception 12 */ 13 public static byte[] httpRequestPostForm(String urlString,Properties formProperties) throws Exception{ 14 15 //設定http要求標頭資訊 16 Properties requestProperties = new Properties(); 17 requestProperties.setProperty("Content-Type", "application/x-www-form-urlencoded"); 18 19 20 //將需要發送的參數拼接成key1=urlencode(value1)&key2=urlencode(value2)&...形式的字串 21 StringBuilder sb = new StringBuilder(); 22 if ((formProperties != null) && (formProperties.size() > 0)) { 23 for (Map.Entry<Object, Object> entry : formProperties.entrySet()) { 24 String key = String.valueOf(entry.getKey()); 25 String value = String.valueOf(entry.getValue()); 26 sb.append(key); 27 sb.append("="); 28 sb.append(encode(value));//urlencode編碼 29 sb.append("&"); 30 } 31 } 32 33 String str = sb.toString(); 34 str = str.substring(0, (str.length() - 1)); // 截掉末尾字元“&” 35 36 return requestPost(urlString, str.getBytes("UTF-8"), requestProperties); 37 } 38 39 40 /** 41 * 發送http請求,並擷取返回的資料 42 * @param urlString 43 * @param requestData 44 * @param requestProperties 45 * @return 46 * @throws Exception 47 */ 48 private static byte[] requestPost(String urlString, byte[] requestData, Properties requestProperties) 49 throws Exception { 50 byte[] responseData = null; 51 HttpURLConnection con = null; 52 53 try { 54 URL url = new URL(urlString); 55 con = (HttpURLConnection) url.openConnection(); 56 57 if ((requestProperties != null) && (requestProperties.size() > 0)) {//佈建要求頭資訊 58 for (Map.Entry<Object, Object> entry : requestProperties 59 .entrySet()) { 60 String key = String.valueOf(entry.getKey()); 61 String value = String.valueOf(entry.getValue()); 62 con.setRequestProperty(key, value); 63 } 64 } 65 66 con.setRequestMethod("POST"); // 置為POST方法 67 68 con.setDoInput(true); // 開啟輸入資料流 69 con.setDoOutput(true); // 開啟輸出資料流 70 71 // 如果請求資料不為空白,輸出該資料。 72 if (requestData != null) { 73 DataOutputStream dos = new DataOutputStream(con 74 .getOutputStream()); 75 dos.write(requestData); 76 dos.flush(); 77 dos.close(); 78 } 79 80 int length = con.getContentLength(); 81 // 如果回複訊息長度不為-1,讀取該訊息。 82 if (length != -1) { 83 DataInputStream dis = new DataInputStream(con.getInputStream()); 84 responseData = new byte[length]; 85 dis.readFully(responseData); 86 dis.close(); 87 } 88 } catch (Exception e) { 89 throw e; 90 } finally { 91 if (con != null) { 92 con.disconnect(); 93 } 94 } 95 96 return responseData; 97 } 98 99 100 /**101 * url解碼102 *103 * @param url104 * @return 解碼後的字串,當異常時返回原始字串。105 */106 private static String decode(String url) {107 try {108 return URLDecoder.decode(url, "UTF-8");109 } catch (UnsupportedEncodingException ex) {110 return url;111 }112 }113 114 /**115 * url編碼116 *117 * @param url118 * @return 編碼後的字串,當異常時返回原始字串。119 */120 private static String encode(String url) {121 try {122 return URLEncoder.encode(url, "UTF-8");123 } catch (UnsupportedEncodingException ex) {124 return url;125 }126 }
發送資料前,需要將資料放入Properties對象中再傳入,這是java.util包中的一個工具類,本來主要作用是讀取java中以.properties結尾的設定檔,關於這個推薦http://www.cnblogs.com/hyyq/p/7399525.html 。當然,這裡完全也可以用Map集合來實現。
發送資料後,服務端可以通過request.getParameter()方法來獲得參數值,也可以通過request.getParameterMap()來擷取,它返回的是一個Map<String,String[]>類型的值,因為我們知道表單有 如性別之類的屬性是有兩個值的。
小結:通過http類比表單提交資料,其實和普通的資料提交也是換湯不換藥。
參考:http://blog.163.com/xing_mu_1/blog/static/6614290201031310207158/
HTTP通訊類比表單提交資料