Spring RESTFul客户端 - RestTemplate。有奇怪的东西,请让我知道

时间:2016-03-29 04:33:56

标签: spring resttemplate

我使用ResTemplate在CLient中发布用户对象。但是当我使用方法postForObject时,会发生未解决的编译问题The method postForObject(URI, Object, Class<T>) in the type RestTemplate is not applicable for the arguments (URL, User, Class<User>)。我真的不明白???

此处归档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"));
    }

此处归档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);
    }

我已编辑String uri但遇到新的关注错误:

  

2016年3月29日下午1:57:43 org.springframework.web.client.RestTemplate   handleResponseError警告:POST请求   &#34; http://localhost:8080/rest/user/create&#34;结果是400(差   请求);在线程&#34; main&#34;中调用错误处理程序异常   org.springframework.web.client.HttpClientErrorException:400 Bad   请求   org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)     在   org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:588)     在   org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546)     在   org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)     在   org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:330)     在   edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:45)

这里是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 个答案:

答案 0 :(得分:2)

确定。我现在无法给出正确答案。我的猜测是你的用户类。 问题是Http 400错误,您必须在服务器端捕获详细的错误消息 - 才能知道究竟是什么!出错了。使用@ControllerAdvide在spring中定义一个globale异常处理程序(这将帮助您编写所有程序)。这并不复杂!只是复制&amp;将这两个类粘贴到您的项目中并确保它们被执行,如果您无法访问控制台,您将在控制台或http日志文件中获得错误的详细信息

希望这会有所帮助..

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

答案 1 :(得分:0)

我认为问题在于URL对象。尝试创建URI对象或简单字符串,如String url =&#34; http://localhost:8080/rest/user/create&#34 ;;

RestTemplate支持URI或String作为postForObject方法的第一个参数