Spring通过HTTP POST发送JSON数据无法正常工作

时间:2015-12-21 16:04:18

标签: java android json spring post

我有一点问题,我跟随Spring RestTemplate http://docs.spring.io/autorepo/docs/spring-android/1.0.x/reference/html/rest-template.html,做了一个名为POST的POST,但是当服务器得到JSON时,没有收到任何东西,我确信服务器功能正常,我已经测试过了。 有人会知道告诉我我哪里错了吗?

RegisterTaskMessage.java

public class RegisterTaskMessage extends AsyncTask<String, String, String> {

  public RegisterTaskMessage() {

  }

  protected String doInBackground(String... params) {

    Message message = new Message();
    message.setId(555);
    message.setSubject("test params");
    message.setText(params[1]);

    // Set the Content-Type header
    HttpHeaders requestHeaders = new HttpHeaders();
    //requestHeaders.setContentType(new MediaType("application", "json"));
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Message> requestEntity = new HttpEntity<Message>(message, requestHeaders);

    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate();

    // Add the Jackson and String message converters
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    // Make the HTTP POST request, marshaling the request to JSON, and the response to a String
    ResponseEntity<String> responseEntity = restTemplate.exchange(params[0], HttpMethod.POST, requestEntity, String.class);
    String result = responseEntity.getBody();
    return null;
  }
}

MainActivity.java

private void sendRegistrationIdToBackend() {
   new RegisterTaskMessage().execute("127.0.0.1/post.php", id);
}

Message.java

public class Message
{
  private long id;

  private String subject;

  private String text;

  public void setId(long id) {
    this.id = id;
  }

  public long getId() {
    return id;
  }

  public void setSubject(String subject) {
    this.subject = subject;
  }

  public String getSubject() {
    return subject;
  }

  public void setText(String text) {
    this.text = text;
  }

  public String getText() {
    return text;
  }
}

1 个答案:

答案 0 :(得分:1)

使用this框架注释您的类{{1}},因为您的服务器接受数据(注意区分大小写/不区分大小写等)