http方式:post
服务器:JDK8、框架:SpringMVC、Server:tomcat7
ionic 主函数
let data={name:XXX,age:'28'};
public postBody(url: string, data: any) {
let param :URLSearchParams = new URLSearchParams();
param.append('name',data.username);
param.append('age',"28");
let myParam = param.toString();
let headers = new Headers({'Accept': 'application/json;charset=utf-8','Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'});
return this.http.post(url,myParam, new RequestOptions({headers: headers}))
.toPromise()
.then(res => this.handleSuccess(res.json()))
.catch(error => this.handleError(error));
}
回调函数
private handleSuccess(result) {
if (result && !result.success) {
alert(result.userId);
alert(result.userName);
}
return result;
}
private handleError(error: Response | any) {
let msg = '请求失败';
alert(error.status);
if (error.status == 0) {
msg = '请求地址错误';
}
if (error.status == 400) {
msg = '请求无效';
}
if (error.status == 404) {
msg = '请求资源不存在';
}
console.log(error);
alert(msg);
return {success: false, msg: msg};
}
java服务器
@RequestMapping(value="/login" ,method=RequestMethod.POST)
@ResponseBody
public Map<String, String> getUserPost(HttpServletRequest request,HttpServletResponse response,User user){
response.setHeader("Access-Control-Allow-Origin", "*");
Map<String, String> userMap = new HashMap<String, String>();
//String name = request.getQueryString();
userMap.put("msg", "成功");
userMap.put("userName", user.getName());
userMap.put("userId", "111111111111");
return userMap;
}