今天遇到一個很惡心的問題卖局,從ios發(fā)過來的post請求怎么都無法識別,可是在web端發(fā)送確實(shí)很正常的茅坛。過程如下:
1.在chrome瀏覽器里隨便打開一個網(wǎng)頁案怯,F(xiàn)12打開控制臺,然后植入jquery
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://libs.baidu.com/jquery/1.9.1/jquery.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
2.發(fā)送post請求
$.post(
"http://192.168.2.4/app/api/blackList/query/name",
{name: "王剛", currentPage: "1"},
function (txt) {
console.log(txt);
}
)
返回的數(shù)據(jù)正常:
Paste_Image.png
通過打斷點(diǎn)調(diào)試發(fā)現(xiàn)江场,
ios端發(fā)來的請求>content-type:application/json
web方式發(fā)來的請求>content-type:application/x-www-form-urlencoded; charset=UTF-8
到這里纺酸,問題就好解決了,前者是一個字符串址否,可以在代碼里加上@RequestBody實(shí)現(xiàn)轉(zhuǎn)換餐蔬,同時,將web傳遞的content-type修改一下即可(不能直接使用$.post佑附,這對于開發(fā)者而言可不夠友好)
$.ajax(
{
type: "post",
contentType:"application/json",
url: "http://192.168.2.4/app/api/blackList/query/name",
data: JSON.stringify({name:"王剛",currentPage:"1"}),
success: function(data){
console.log(data)
}
}
)
斟酌再三樊诺,決定還是保留對傳統(tǒng)web端jquery.post()方式的支持,同時支持ios序列化傳遞過來的參數(shù)音同,第一版先進(jìn)行header判斷词爬,遇到application/json的content-type,就從request取出inputstream权均,手動轉(zhuǎn)化
controller的代碼如下:
@ApiOperation(value = "姓名查詢", notes = "首次訪問時currentPage傳1")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "名稱", required = true, dataType = "String"),
@ApiImplicitParam(name = "currentPage", value = "當(dāng)前是第幾頁", required = true, dataType = "String")})
@PostMapping(value = "/api/blackList/query/name")
public String nameQuery(BlackListParam param, HttpServletRequest request) throws IOException {
String contentType = request.getHeader("Content-Type");
if (contentType.endsWith("application/x-www-form-urlencoded")) {
} else if (contentType.endsWith("application/json")) {
String string = HttpToolkit.getContent(request.getInputStream(), "UTF-8");
param = mapper.readValue(string, BlackListParam.class);
}
logger.info("進(jìn)入nameQuery,name=" + param.getName() + "¤tPage=" + param.getCurrentPage());
int currentPageInt = Integer.parseInt(param.getCurrentPage());
String result = blackListApiService.nameQuery(param.getName(), currentPageInt);
return result;}
HttpToolkit里面的getContent部分的代碼:
public static String getContent(InputStream is, String charset) {
String pageString = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuffer sb = null;
try {
isr = new InputStreamReader(is, charset);
br = new BufferedReader(isr);
sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
pageString = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null){
is.close();
}
if(isr!=null){
isr.close();
}
if(br!=null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
sb = null;
}
return pageString;
}