接口代碼:
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST)/*只允許POST方式調用此接口*/
public returnType functionName(/*POST數據內容*/@RequestBody parameterType parameterName,HttpServletRequest request) throws Exception {}
配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
依賴文件:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
邏輯代碼:
/*如果是List數據 在接收到數據之後 需要轉換類型*/
/*否則不需要轉換*/
ObjectMapper mapper = new ObjectMapper();
for (int i = 0; i < behaviorList.size(); i++) {
/*由於客戶端POST過來的List是LinkedHashMap類型的數據
* 所以需要用ObjectMapper進行解析轉換*/
ClassName clazz = mapper.convertValue(List.get(i),ClassName.class);
}
實體類:
如果訪問端是C# DateTime類型要重置為String類型,否則服務端無法解析
訪問端(C#):
/*POST之前 要先將實體類轉換為JSon字符串 然後再轉換成Byte數組*/
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri);
httpReq.Method = "POST";
httpReq.Accept = "*/*";
httpReq.ContentType = "application/json; charset=utf-8";
byte[] buffer = Encoding.UTF8.GetBytes(dataJsonString);
httpReq.ContentLength = buffer.Length;
httpReq.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
Stream respStream = httpResp.GetResponseStream();
StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
string result = respStreamReader.ReadToEnd();
以上是個人遇到問題時候 嘗試了一天時間找到的解決辦法
本人java菜鳥 解決方案也許比較片面或老舊或笨拙 望大神指教
也希望能夠幫到遇到同樣問題的朋友