Vincenzo Guglielmi
Vincenzo Guglielmi

Reputation: 41

Spring Send JSON data via HTTP POST not working

I have a little problem, I followed the lead of Spring RestTemplate http://docs.spring.io/autorepo/docs/spring-android/1.0.x/reference/html/rest-template.html, to make a called POST, but when the server should get the JSON, does not receive anything, I'm sure that the server functions, I have already tested. someone would know tell me where I'm wrong?

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

Upvotes: 1

Views: 413

Answers (1)

Claudio Pomo
Claudio Pomo

Reputation: 2472

Use this framework to annotate your class Message as your server accept data (be careful to case sensitive/case insensitive and so one)

Upvotes: 1

Related Questions