如何向BayeuxClient添加请求头

问题描述 投票:0回答:2
  String url = "some_url";
  HttpClient httpClient = new HttpClient();
  httpClient.start();
  Map<String, Object> options = new HashMap<String, Object>();
  LongPollingTransport transport = new LongPollingTransport(options, httpClient);
  BayeuxClient client = new BayeuxClient(url, transport);
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener() {
     public void onMessage(ClientSessionChannel channel, Message message) {
         System.out.println(message);
     }
  });
  client.handshake();

得到

{"failure":{"exception":"org.cometd.common.TransportException: {httpCode=403}","message":{"supportedConnectionTypes":["long-polling"],"channel":"/meta/handshake","id":"2","version":"1.0"},"httpCode":403,"connectionType":"long-polling"},"channel":"/meta/handshake","id":"2","subscription":null,"successful":false}

所以我的第一个猜测是添加授权标头。我怎样才能做到这一点? Jetty 9 用于服务器和客户端代码库。

cometd request-headers bayeux
2个回答
1
投票

请查看这个测试用例,它展示了如何做到这一点。


0
投票

这是在 CometD 8 中如何在 JettyHttpClientTransport 中添加授权。从 CometD 5 开始,LongPollingTransport 被 JettyHttpClientTransport 取代

https://github.com/cometd/cometd/blob/6b24fff9c508a6d2d6ce4302897ad5e45af48e86/cometd-java/cometd-java-client/cometd-java-client-http/cometd-java-client-http-tests/src/test/ java/org/cometd/client/http/HandshakeWithAuthenticationTest.java#L79C1-L87C11:

ClientTransport transport = new JettyHttpClientTransport(null, httpClient) {
    @Override
    protected void customize(Request request) {
        String authorization = userName + ":" + password;
        byte[] bytes = Base64.getEncoder().encode(authorization.getBytes(StandardCharsets.UTF_8));
        String encoded = new String(bytes, StandardCharsets.UTF_8);
        request.headers(headers -> headers.put("Authorization", "Basic " + encoded));
    }
};
    BayeuxClient client = new BayeuxClient(cometdURL, transport);
© www.soinside.com 2019 - 2024. All rights reserved.