[英]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.我的问题是当我尝试此操作时出现媒体类型错误,然后我更改了 header。现在我收到 500 错误。 The problem isnt the api, on postman it works perfectly, am I doing something wrong in my code when requesting a post?
问题不在于 api,在 postman 上它工作得很好,请求发帖时我的代码是不是做错了什么?
My object model我的 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;
}
}
My Controller It should send a post request with a object body, the emails get sent我的 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());
}
You must to convert EmailModel
to json
format by ObjectMapper
您必须通过
ObjectMapper
将EmailModel
转换为json
格式
ObjectMapper objectMapper = new ObjectMapper();
String data = objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(em);
and change POST
to:并将
POST
更改为:
.POST(HttpRequest.BodyPublishers.ofString(data))
See more about ObjectMapper查看有关ObjectMapper的更多信息
Capture requests and cookies(on the left side of setting icon) ->Request ->port and put the port number there捕获请求和cookie(在设置图标的左侧)->请求->端口并将端口号放在那里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.