[英]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());
}
您必須通過ObjectMapper
將EmailModel
轉換為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.