通过 REST 传输对象



我一直在尝试使用 rest 将对象从一个应用程序发送到另一个应用程序。

寄件人:

@Controller
public class Sender {
@RequestMapping(value = "/comMessageApp-api/getMessages")
public String restGetMessages() {
String url = "http://localhost:8079/comMessageApp-api/responseMessages";
HttpEntity<Dto2> entity = new HttpEntity<>(new Dto2());
ResponseEntity<Dto2> response = restTemplate.exchange(url, HttpMethod.POST, entity, Dto2.class);
}
}

接收器:

@RestController
public class Receiver {
@RequestMapping(value = "/comMessageApp-api/responseMessages")
public void restResponseMessages(HttpEntity<Dto2> request) {
System.out.println(request.getBody());       
}
}

DTO:

public class Dto2 {
private String string = "Test string";
public Dto2() {
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}

杰克逊使用序列化/反序列化。

任何想法,为什么在接收器中打印的request.getBody((是空的??? 我尝试在 HttpEntity 和 RequestEntity 中发送对象。这两种情况都没有成功。在接收端,我总是得到空。

您的发送方(客户端(端非常接近,但您的服务器端不返回值,因此将类型更改为 Void:

ResponseEntity<Void> response = restOps.exchange(url, HttpMethod.POST, entity, Void.class);

您的接收方(服务器(端也没有完全正确设置,您需要将HTTP方法设置为[编辑] POST。 您还需要告诉 Spring 将请求的正文(您的休息有效负载(映射到参数上;

@RequestMapping(value = "/comMessageApp-api/responseMessages", method=RequestMethod.POST)
public void recieveDto (@RequestBody final Dto dto) {
System.out.println(dto.toString());
}

[编辑] Brainfart,http方法应该设置为POST接收注释。

[进一步建议] 403错误可能是由于Spring Security造成的,如果您已将其打开(如果您不确定,请检查您的POM(,请尝试此操作;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests().
antMatchers("/**").permitAll();
}
}

一旦你知道它有效,你就会想要加强安全性。

尝试使用@RequestMapping(method = RequestMethod.POST, produces = "application/json", consumes = "application/json")

最新更新