最近做項(xiàng)目時,發(fā)現(xiàn)手機(jī)客戶端通過http協(xié)議post方式上傳數(shù)據(jù)到服務(wù)端,在服務(wù)器端通過request.getInputStream()能獲取到相應(yīng)的數(shù)據(jù),但用request.getParameter()卻獲取不到數(shù)據(jù)。這是怎么回事呢,后來發(fā)現(xiàn)這種情況跟form表單的屬性 enctype有關(guān)系。
HTML中的form表單有一個關(guān)鍵屬性 enctype=application/x-www-form-urlencoded 或multipart/form-data。
1、enctype="application/x-www-form-urlencoded"是默認(rèn)的編碼方式,當(dāng)以這種方式提交數(shù)據(jù)時,HTTP報文中的內(nèi)容是:
Html代碼
<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提供了對這種編碼方式解碼的支持,只需要調(diào)用ServletRequest 類中的getParameter()方法就可以得到表單中提交的數(shù)據(jù)。
2、在傳輸大數(shù)據(jù)量的二進(jìn)制數(shù)據(jù)時,必須將編碼方式設(shè)置成enctype="multipart/form-data",當(dāng)以這種方式提交數(shù)據(jù)時,HTTP報文中的內(nèi)容是:
Html代碼
<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> 如果以這種方式提交數(shù)據(jù)就要用request.getInputStream()或request.getReader()來獲取提交的數(shù)據(jù) ,用 request.getParameter()是獲取不到提交的數(shù)據(jù)的。
最后注意request.getParameter()、request.getInputStream()、request.getReader()這三種方法是有沖突的,因?yàn)榱髦荒鼙蛔x一次。比如: 當(dāng)form表單內(nèi)容采用enctype=application/x-www-form-urlencoded編碼時,先通過調(diào)用request.getParameter()方法獲取數(shù)據(jù)后,再調(diào)用request.getInputStream()或request.getReader()已經(jīng)獲取不到流中的內(nèi)容了,因?yàn)樵谡{(diào)用 request.getParameter()時系統(tǒng)可能對表單中提交的數(shù)據(jù)以流的形式讀了一次,反之亦然。
當(dāng)form表單內(nèi)容采用enctype=multipart/form-data編碼時,調(diào)用request.getParameter()獲取不到數(shù)據(jù),即使已經(jīng)調(diào)用了request.getParameter()方法也可以再通過調(diào)用request.getInputStream()或request.getReader()獲取表單中的數(shù)據(jù),但request.getInputStream()和request.getReader()在同一個響應(yīng)中是不能混合使用的,如果混合使用會拋異常的。
新聞熱點(diǎn)
疑難解答