簡體   English   中英

試圖在 java spring 中呼叫/發布第三方 api

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

我的問題是當我嘗試此操作時出現媒體類型錯誤,然后我更改了 header。現在我收到 500 錯誤。 問題不在於 api,在 postman 上它工作得很好,請求發帖時我的代碼是不是做錯了什么?

我的 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 = "[chrispotjnr@gmail.com,chris@mqattach.com]";
        this.eventCode = "DEFAULT";
        this.metaData = metaData;
    }
}

我的 Controller 它應該發送一個正文為 object 的帖子請求,電子郵件已發送

@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());
}

郵遞員圖片

您必須通過ObjectMapperEmailModel轉換為json格式

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

並將POST更改為:

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

查看有關ObjectMapper的更多信息

捕獲請求和cookie(在設置圖標的左側)->請求->端口並將端口號放在那里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM