0

我一直在开发一个利用 openshift api 的 Java 应用程序。特别是 OpenShift 部署配置

我试图设置一个观察者,但我的响应体从未被调用。我已经能够从“非观察者”API 调用中获得响应。我正在使用 groovy httpbuilder 库来满足我的要求

def http = new HTTPBuilder(<<URL TO OPENSHIFT>>)
try {
    http.get(path: '/oapi/v1/watch/namespaces/myproject/deploymentconfigs', contentType: "application/json") { resp, reader ->
        println(resp)
        return reader
    }
} catch (HttpResponseException e) {
    System.out.println(e)
}

请就在我的应用程序中设置 OpenShift 观察者的路径提出建议。永远不会抛出错误消息。minishift logs -f 也没有提供任何反馈。另请注意,我已经让它与 curl 命令一起使用,记录在 api 中

4

1 回答 1

0

您可以使用 OKHttpClient 为您处理 http websocket 升级协议。请注意,旧版本的 minishift 在尝试发出 websocket 连接请求时需要查询参数“access_token”

        OkHttpClient client = new OkHttpClient();
        def token = token
        Request request = new Request.Builder()
                .get()
                .url("https://<<IP>>/oapi/v1/watch/namespaces/<<namespace>>/deploymentconfigs?watch=true&access_token=<<token>>")
                .addHeader("Accept", "application/json")
                .addHeader("Connection", "close")
                .addHeader("Sec-WebSocket-Protocol",'base64url.bearer.authorization.k8s.io.' + Base64.getEncoder().encodeToString(token.getBytes()))
                .addHeader('Origin', 'https://<<IP>>')
                .build()
        WebSocketListener websocketListener= new WebSocketListenerImpl()
        client.newWebSocket(request, websocketListener)

WebSocketListenerImpl 类

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketListenerImpl extends WebSocketListener {

    public WebSocketListenerImpl() {
        super();
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        print "WEBSOCKET OPEN"
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        super.onMessage(webSocket, text);
        print "WEBSOCKET RECEIVED"

    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        super.onMessage(webSocket, bytes);
        print "WEBSOCKET OPEN"

    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        super.onClosing(webSocket, code, reason);
        print "WEBSOCKET CLOSING"

    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);
        print "WEBSOCKET CLOSED"

    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, @javax.annotation.Nullable Response response) {
        super.onFailure(webSocket, t, response);
        println "WEBSOCKET FAILED"

    }
}
于 2020-04-01T22:17:30.770 回答