手機客戶端post請求獲得不參數

最近作項目時,發現手機客戶端經過http協議post方式上傳數據到服務端,在服務器端經過request.getInputStream()能獲取到相應的數據,但用request.getParameter()卻獲取不到數據。這是怎麼回事呢,後來發現這種狀況跟form表單的屬性 enctype有關係。php

HTML中的form表單有一個關鍵屬性 enctype=application/x-www-form-urlencoded 或multipart/form-data。html

 

一、enctype="application/x-www-form-urlencoded"是默認的編碼方式,當以這種方式提交數據時,HTTP報文中的內容是:服務器


<span style="font-size: small;">POST /post_test.php HTTP/1.1 
Accept-Language: zh-CN
User-Agent: Mozilla/4.0 
Content-Type: application/x-www-form-urlencoded 
Host: 192.168.12.102
Content-Length: 42
Connection: Keep-Alive
Cache-Control: no-cache
 
title=test&content=%B3%AC%BC%B6%C5%AE%C9%FA&submit=post+article 
</span>

Servlet的API提供了對這種編碼方式解碼的支持,只須要調用ServletRequest 類中的getParameter()方法就能夠獲得表單中提交的數據。app


二、在傳輸大數據量的二進制數據時,必須將編碼方式設置成enctype="multipart/form-data",當以這種方式提交數據時,HTTP報文中的內容是:

<span style="font-size: small;">POST /post_test.php?t=1 HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0  
Content-Type: multipart/form-data; boundary=---------------------------7dbf514701e8
Accept-Encoding: gzip, deflate
Host: 192.168.12.102
Content-Length: 345
Connection: Keep-Alive
Cache-Control: no-cache
 
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="title"
test
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="content"
....
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="submit"
post article
-----------------------------7dbf514701e8--</span>

若是以這種方式提交數據就要用request.getInputStream()或request.getReader()來獲取提交的數據用 request.getParameter()是獲取不到提交的數據的。post

 

 

最後注意request.getParameter()、request.getInputStream()、request.getReader()這三種方法是有衝突的,由於流只能被讀一次。
好比:
當form表單內容採用enctype=application/x-www-form-urlencoded編碼時,先經過調用request.getParameter()方法獲取數據後,再調用request.getInputStream()或request.getReader()已經獲取不到流中的內容了,由於在調用 request.getParameter()時系統可能對錶單中提交的數據以流的形式讀了一次,反之亦然。
大數據

 

當form表單內容採用enctype=multipart/form-data編碼時,調用request.getParameter()獲取不到數據,即便已經調用了request.getParameter()方法也能夠再經過調用request.getInputStream()或request.getReader()獲取表單中的數據,但request.getInputStream()和request.getReader()在同一個響應中是不能混合使用的,若是混合使用會拋異常的。編碼

來源:http://well-lf.iteye.com/blog/1543807
相關文章
相關標籤/搜索