Spring WebSocket Connecting with SockJS to a different domain

前端 未结 4 1365
有刺的猬
有刺的猬 2021-02-02 09:30

WebSockets in Spring is a rather new topic that I;m tiring to find a bit more.

My problem is with connecting to a service from a different domain, I\'m working on with

4条回答
  •  轮回少年
    2021-02-02 09:42

    To anyone getting to this ticket because of the 403 Forbidden answer when trying to connect through a SockJsClient to a different domain:

    The problem arises when trying to make a GET to the /info Url, as part of the handshaking. The response actually returns a 200 via WGET as well as via browser. Only through SockJsClient it doesn't work.

    After trying different solutions, the only one that really fixed the issue is to write a class that implements Transport and InfoReceiver. In this way the developer can directly handle this part of the handshake. Basically you make the work in the executeInfoRequest() method:

    @Override
    public String executeInfoRequest(URI infoUrl, HttpHeaders headers) {
        HttpGet getRequest = new HttpGet(infoUrl); // eventually add headers here
        HttpClient client = HttpClients.createDefault();
    
        try {
            HttpResponse response = client.execute(getRequest);
            List responseOutput = IOUtils.readLines(response.getEntity().getContent());
    
            return responseOutput.get(0);
        } catch (IOException ioe) {
            ...
        }
    }
    

    I defined TransportType.XHR as transport type.

提交回复
热议问题