Spring MVC 接收POST表單請求,獲取引數總結
阿新 • • 發佈:2018-12-21
前段時間遇到一個問題,在spring mvc 服務端接收post請求時,通過html 表單提交的時候,服務端能夠接收到引數的值。但是使用httpclient4.3構造post請求,卻無法接收到引數的值。
spring 程式碼:
@RequestMapping(value = "login.do", method = RequestMethod.POST) @ResponseBody public String login(String username, String password) throws Exception { return username + ":" + password; }
表單程式碼:
<form action="http://localhost:8080/test/login.do" id="frm" method="post"> name:<input type="text" name="username" id="username"/> </br> psword:<input type="text" name="password" id="password"/> </br> <input id="submit" type="submit" /> </form >
httpclient4.3傳送post程式碼:
@Test public void testMultipartPost() throws IOException { HttpPost httpPost = new HttpPost("http://localhost:8080/test/login.do"); try { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient httpClient = httpClientBuilder.build(); RequestConfig config = RequestConfig.custom().setConnectTimeout(200000 ).setSocketTimeout(200000).build(); httpPost.setConfig(config); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); multipartEntityBuilder.addTextBody("username", "taozi"); multipartEntityBuilder.addTextBody("password", "123"); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); HttpResponse response = httpClient.execute(httpPost); System.out.println(EntityUtils.toString(response.getEntity())); } finally { httpPost.releaseConnection(); } }
一直在查詢原因,為什麼通過httpclient4.3構造的post請求,服務端無法接收到傳輸的引數。比較與html的差異,發現httpclient構造的請求使用的是multipart形式。而表單上傳使用的是預設形式的編碼,x-www-form-urlencoded,所以表單能夠成功。現在找到問題了,將httpclient的構造程式碼,改為x-www-form-urlencoded編碼上傳,
@Test public void testUrlencodedPost() throws IOException { HttpPost httpPost = new HttpPost("http://localhost:8080/test/login.do"); try { CloseableHttpClient client = HttpClients.createDefault(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "taozi")); params.add(new BasicNameValuePair("password", "123")); HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8"); httpPost.setEntity(httpEntity); CloseableHttpResponse response = client.execute(httpPost); System.out.println(EntityUtils.toString(response.getEntity())); } finally { httpPost.releaseConnection(); } }
現在服務端能夠正常的接收到請求了,現在總結一下表單兩種編碼的形式
application/x-www-form-urlencoded 空格轉換為 "+" 加號,特殊符號轉換為 ASCII HEX 值
multipart/form-data 不對字元進行編碼,使用二進位制資料傳輸,一般用於上傳檔案,非文字的資料傳輸。
spring mvc如果要接收 multipart/form-data 傳輸的資料,應該在spring上下文配置
[xml] view plain copy print?- <beanid="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- </bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>
這樣服務端就既可以接收multipart/form-data 傳輸的資料,也可以接收application/x-www-form-urlencoded傳輸的文字資料了。