Daniil Orekhov
Daniil Orekhov

Reputation: 438

Android okhttp: creating WebSocketCall does not work properly

so I am trying to figure out how to establish wss connection for my android app and here is the problem I am facing right now:

Here is my ApiConnection class:

public class ApiConnection implements WebSocketListener {

    private static String URL_ADDRESS = "https://148.251.90.48/websocket/";

    final static OkHttpClient client = createClient();

    public static final MediaType JSON
        = MediaType.parse("application/json; charset=utf-8");

    public String doPostRequest(String json) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
            .url(URL_ADDRESS)
            .post(body)
            .build();

        WebSocketCall call = WebSocketCall.create(client, request);
        System.out.println("HELLO WORLD");
        call.enqueue(this);

        return "";
    }

    private static OkHttpClient createClient() {

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
            .connectTimeout(0, TimeUnit.MILLISECONDS)
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .writeTimeout(0, TimeUnit.MILLISECONDS)
            .hostnameVerifier((hostname, session) -> true);

        return clientBuilder.build();
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        System.out.println("API CONNECTION ON OPEN");
    }

    @Override
    public void onFailure(IOException e, Response response) {
        System.out.println("API CONNECTION ON FAILURE");
    }

    @Override
    public void onMessage(ResponseBody message) throws IOException {
        System.out.println("API CONNECTION ON MESSAGE");
    }

    @Override
    public void onPong(Buffer payload) {
        System.out.println("API CONNECTION ON PONG");
    }

    @Override
    public void onClose(int code, String reason) {
        System.out.println("API CONNECTION ON CLOSE");
    }
}

The problem I am facing is that nothing is executed after this line: WebSocketCall call = WebSocketCall.create(client, request);

So, "HELLO WORLD" is never printed. And none of the "onOpen", "onFailure" etc. methods are run through either. This makes it impossible to work with the response from the server. What's wrong with this code? How would I fix this problem?

PS I am very new to this, so please let me know if something else is weird here :)

Thank you :)

Upvotes: 0

Views: 1198

Answers (0)

Related Questions