Home > Software engineering >  Trying to call/post a third party api in java spring
Trying to call/post a third party api in java spring

Time:04-25

My issue is when I try this I get a media type error, then I changed the header. Now I receive a 500 error. The problem isnt the api , on postman it works perfectly , am I doing something wrong in my code when requesting a post?

My object model

private String module;
    private String notificationGroupType;
    private String notificationGroupCode;
    private String notificationType;
    private String inLineRecipients;
    private String eventCode;
    private HashMap<String, Object> metaData;

    public EmailModel() {
        this.module = "CORE";
        this.notificationGroupType ="PORTAL";
        this.notificationGroupCode = "DEFAULT";
        this.notificationType =  "EMAIL";
        this.inLineRecipients ="[[email protected],[email protected]]";
        this.eventCode = "DEFAULT";
        this.metaData = metaData;
    }
 

My Controller It should send a post request with a object body, the emails get sent

 private EmailModel em;
    @RequestMapping(value = "test", method = RequestMethod.Post)
    public void post() throws Exception {
        String uri= "TestUrl";


        EmailModel em = new EmailModel();
                EmailModel data =em;

        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder()
                .headers("Content-Type", "application/json")
                .uri(URI.create(uri))
                .POST(HttpRequest.BodyPublishers.ofString(String.valueOf(data)))
                .build();

        HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        System.out.println(em);
        System.out.println(response.statusCode());

    }

postmanImage

CodePudding user response:

You must to convert EmailModel to json format by ObjectMapper

ObjectMapper objectMapper = new ObjectMapper();
String data = objectMapper
      .writerWithDefaultPrettyPrinter()
      .writeValueAsString(em);

and change POST to :

.POST(HttpRequest.BodyPublishers.ofString(data))

See more about ObjectMapper

  • Related