简体   繁体   中英

Call WS Rest Java with AngularJS

I've a problem with call WS Rest Java. I call the WS but the parameters isn't passed.

My java code:

@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();
    }
}

Angular call:

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'}
  });

If i log data on angular data are set, the call working but i've an error when i create AccountDAO object because the parameters are null. To test the parameters values i create a file and put here the value, the content are this:

name: null

Surname: null

Email: null

Phone: null

Skype: null

Password: null

Any one have idea why not pass the parameters?

Thanks!

Solved:

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'}
  })

Thanks grizzly!

You are sending data as JSON. Change it to form data string:

  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'}
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM