使用 AngularJS 调用 WS Rest Java



我在调用WS Rest Java时遇到了问题。我调用 WS,但参数未传递。

我的java代码:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response setUser(@FormParam("name") String name, @FormParam("surname") String surname, @FormParam("email") String email,
                        @FormParam("phone") String phone, @FormParam("skype") String skype, @FormParam("password") String password){
    try {
        FileOutputStream fis =  new FileOutputStream("/home/File.txt");
        PrintStream ps = new PrintStream(fis);
        String s = "name: "+name+"nSurname: "+surname+"nEmail: "+email+"nPhone: "+phone+"nSkype: "+skype+"nPassword: "+password;
        ps.println(s);
        ps.close();
        fis.close();
        UserDAO userdao = new UserDAO(0,name,surname,email,phone,skype);
        userdao.save();
        ...
        return Response.status(200).entity(new ObjectMapper().writeValueAsString("OK!")).header("Access-Control-Allow-Origin", "*").build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(500).entity("ERROR!").header("Access-Control-Allow-Origin", "*").build();
    }
}

角度调用:

data = {
    name: $scope.reg_name,
    surname: $scope.reg_surname,
    email: $scope.reg_email,
    phone: $scope.reg_phone,
    skype: $scope.reg_skype,
    password: $scope.reg_password
  }
$http.post(baseUrl+'user/',data,{
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  });

如果我在角度数据上记录数据,则调用有效,但是在创建 AccountDAO 对象时出现错误,因为参数为空。为了测试参数值,我创建了一个文件并在此处放置值,内容如下:

名称:空

姓氏:空

电子邮件:空

电话:空

Skype:空

密码:空

有人知道为什么不传递参数吗?

谢谢!

解决:

data = "name=" + $scope.reg_name +
"&surname=" + $scope.reg_surname +
"&email=" + $scope.reg_email +
"&phone=" + $scope.reg_phone +
"&skype=" + $scope.reg_skype +
"&password=" + $scope.reg_password;
  }
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  })

谢谢灰熊!

您正在以 JSON 形式发送数据。将其更改为数据字符串形式:

  data = "name=" + $scope.reg_name +
    "&surname=" + $scope.reg_surname +
    "&email=" + $scope.reg_email +
    "&phone=" + $scope.reg_phone +
    "&skype=" + $scope.reg_skype +
    "&password=" + $scope.reg_password;
  }
$http.post(baseUrl+'user/',data,{
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  })

相关内容

  • 没有找到相关文章

最新更新