Request Post API Messenger with Spring Boot

2

I need to create a post method that returns this information to the Messenger API with Spring Boot, if anyone can give a light thanks.

The example below is found in the Facebook Developers documentation

curl -X POST -H "Content-Type: application/json" -d '{
  "messaging_type": "<MESSAGING_TYPE>",
  "recipient": {
    "id": "<PSID>"
  },
  "message": {
    "text": "hello, world!"
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>"
    
asked by anonymous 20.06.2018 / 07:08

1 answer

1

You need the class RestTemplate , of the Spring Boot. It allows you to perform HTTP requests very easily.

For this request, you need 3 things: the headers, the json with the data, the URL to be called. To create json, add the following dependency to your project:

compile group: 'org.json', name: 'json', version: '20180130'

Here is the commented code:

public void post(String token) {
  String url = "https://graph.facebook.com/v2.6/me/messages? 
    access_token=".concat(token);

  //setando o header da requisição. Veja se a documentação pede algum
  //outro header além desse e adicione, se necessário
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setContentType(MediaType.APPLICATION_JSON);

  //Montando o json esperado pelo Facebook
  JSONObject json = new JSONObject();
  json.put("messaging_type", "Algum valor aqui");

  JSONObject id = new JSONObject();
  id.put("id", "valor do ID aqui");
  json.put("recipient", id);

  JSONObject text = new JSONObject();
  text.put("text", "hello, world!");
  json.put("message", text);

  //Criando o objeto que representa a requisição a ser enviada
  HttpEntity <String> httpEntity = new HttpEntity <String> (json.toString(), httpHeaders);
  RestTemplate restTemplate = new RestTemplate();

  //Chamada propriamente dita, com a resposta do Facebook mapeada para uma String
  String response = restTemplate.postForObject(url, httpEntity, String.class);
}

By printing the json that was mounted, we have this result:

{
  "messaging_type": "Algum valor aqui",
  "recipient": {
    "id": "valor do ID aqui"
  },
  "message": {
    "text": "hello, world!"
  }
}
    
20.06.2018 / 21:09