Chris
Chris

Reputation: 25

Trying to call/post a third party api in java spring

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

public class EmailModel {
    
    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

@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

Upvotes: 1

Views: 2520

Answers (2)

Krushna Patil
Krushna Patil

Reputation: 1

Capture requests and cookies(on the left side of setting icon) ->Request ->port and put the port number there

Upvotes: 0

Kai-Sheng Yang
Kai-Sheng Yang

Reputation: 1716

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

Upvotes: 1

Related Questions