0
votes

I'm using ResTemplate to post User object in CLient. But When i use method postForObject then occur Unresolved compilation problem The method postForObject(URI, Object, Class<T>) in the type RestTemplate is not applicable for the arguments (URL, User, Class<User>). I really don't understand ???

Here file RestClientTest.java`

public class RestClientTest {

    public static void main(String[] args) throws IOException{
//      System.out.println("Rest Response" + loadUser("quypham"));
//      URL url = new URL("http://localhost:8080/rest/user/create");
//      rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
//      rt.getMessageConverters().add(new StringHttpMessageConverter());
//      Map<String,String> vars = new HashMap<String,String>();

        RestTemplate rt = new RestTemplate();
        User user = new User();
        user.setUserName("datpham");
        user.setPassWord("12345");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,1960);
        user.setBirthDay(calendar.getTime());
        user.setAge(12);
        String uri = new String("http://localhost:8080/rest/user/create");
        User returns = rt.postForObject(uri, user,User.class);

//      createUser(user);
        System.out.println("Rest Response" + loadUser("datpham"));
    }

Here file UserRestServiceController

@Controller
public class UserRestServiceController {
    @Autowired
    public  UserDao userDao;
    @RequestMapping(value = "/rest/user/create",method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void addUser(@RequestBody User user){
        userDao.save(user);
    }

I have edited String uri but encounter new following error:

Mar 29, 2016 1:57:43 PM org.springframework.web.client.RestTemplate handleResponseError WARNING: POST request for "http://localhost:8080/rest/user/create" resulted in 400 (Bad Request); invoking error handler Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:588) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:330) at edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:45)

Here User.java

@Entity
@Table(name = "brotheruser",uniqueConstraints={@UniqueConstraint(columnNames="username")})
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
//  @Enumerated(EnumType.STRING)
//  @Column(name = "gender", nullable = false)
//   
//  public Gender getGender() {
//      return gender;
//  }
//  public void setGender(Gender gender) {
//      this.gender = gender;
//  }
    @Id
    @Column(name = "username", unique = true, nullable = false)
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    @Column(name = "password", nullable = false)
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    @JsonSerialize(using = DateSerializer.class)
//  @JsonDeserialize(using = DateDeserializer.class)
    @Column(name = "birthday", nullable = false)
    public Date getBirthDay() {


        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }
    @Column(name="age", nullable = false)
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    private String userName;
    private String passWord;
    private Date birthDay;
    private Integer age;

//  private Gender gender;


}
2
Show us your User class!, plskamokaze
why are you using DtaeSerializer.class - you dont have ro...Date Types are automatically serializedkamokaze

2 Answers

2
votes

Ok. I can't give the correct answer right now. My guess is thts in your User class. The thing is with Http 400 errors, that you have to catch a detailed error message on the server side -to know what is exactly! going wrong. Define a globale exception handler in spring with @ControllerAdvide (and this will help you inwith everything you programm). It's not complicated! just copy & paste the two classes into your project and make sure they get executed, and you will get a detailed outup of the error on the console or the http log file if you don't have access to console

hope this helps ..

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.*;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return super.handleNoHandlerFoundException(ex, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return super.handleExceptionInternal(ex, body, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
        List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
        String error;
        for (FieldError fieldError : fieldErrors) {
            error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
            errors.add(error);
        }
        for (ObjectError objectError : globalErrors) {
            error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
            errors.add(error);
        }
        RestResponseErrorMessage errorMessage = new RestResponseErrorMessage(errors);
        return new ResponseEntity(errorMessage, headers, status);
    }

    @Override
    protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String unsupported = "Unsupported content type: " + ex.getContentType();
        String supported = "Supported content types: " + MediaType.toString(ex.getSupportedMediaTypes());
        RestResponseErrorMessage errorMessage = new RestResponseErrorMessage(unsupported, supported);
        return new ResponseEntity(errorMessage, headers, status);
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Throwable mostSpecificCause = ex.getMostSpecificCause();
        RestResponseErrorMessage errorMessage;
        if (mostSpecificCause != null) {
            String exceptionName = mostSpecificCause.getClass().getName();
            String message = mostSpecificCause.getMessage();
            errorMessage = new RestResponseErrorMessage(exceptionName, message);
        } else {
            errorMessage = new RestResponseErrorMessage(ex.getMessage());
        }
        return new ResponseEntity(errorMessage, headers, status);
    }
}

import javax.xml.bind.annotation.XmlRootElement;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by pk on 08.03.2016.
 */
@XmlRootElement
public class RestResponseErrorMessage {


        private List<String> errors;

        public RestResponseErrorMessage() {
        }

        public RestResponseErrorMessage(List<String> errors) {
            this.errors = errors;
        }

        public RestResponseErrorMessage(String error) {
            this(Collections.singletonList(error));
        }

        public RestResponseErrorMessage(String ... errors) {
            this(Arrays.asList(errors));
        }

        public List<String> getErrors() {
            return errors;
        }

        public void setErrors(List<String> errors) {
            this.errors = errors;
        }
    }
0
votes

I think problem is with URL object. Try creating URI object or simple string like String url = "http://localhost:8080/rest/user/create";

RestTemplate supports URI or String as first parameter for for postForObject method