【问题标题】:Transferring an object via REST通过 REST 传输对象
【发布时间】:2017-07-08 17:23:08
【问题描述】:

我一直在尝试使用 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;
    }
}

Jackson 用于序列化/反序列化。

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

【问题讨论】:

  • 如果您尝试将 DTO 发送到接收方,那么您应该使用 POST 方法而不是 GET。 GET 用于从另一端检索数据。如果要从 Receiver 检索 DTO,则需要在 Receiver 中创建 DTO 并将其返回。
  • 我已将其更改为发布。但现在我在发件人端收到“org.springframework.web.client.HttpClientErrorException: 403 null”异常。请求永远不会到达接收者
  • 请提供minimal reproducible example。在这种情况下,您可能需要向最少的完整程序展示:一个用于服务器,一个用于客户端。

标签: java rest spring-mvc


【解决方案1】:

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

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

您的接收器(服务器)端也没有正确设置,您需要将 HTTP 方法设置为 [edited] POST。您还需要告诉 Spring 将请求的主体(您的剩余负载)映射到参数上;

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

[EDIT] Brainfart,http 方法应该设置为 POST on receive annotation。

[进一步建议] 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();
    }
}

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

【讨论】:

  • 不起作用。 'HttpMethod.POST' 在 Sender 端生成 'org.springframework.web.client.HttpClientErrorException: 403 null'
  • 奇怪 - 403 是一个被禁止的消息代码,你在你的应用程序中使用 Spring Security 吗?
  • 感谢您对 Spring Security 的提醒。是的,我使用了它,但我完全忘记了需要禁用 csrf 保护。现在休息工作
【解决方案2】:

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

【讨论】:

  • 他们为什么要这样做?它有什么不同?你为什么这么认为?他们的原始代码有什么问题?没有这些细节,你的回答是毫无用处的。
猜你喜欢
  • 1970-01-01
  • 2016-02-21
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多