简体   繁体   中英

OkHttp Reverse Http

How to implement reverse http as described in link using OkHttp

Currently my implementation is something like Issue is I have to parse http responses which I don't feel safe, its just a coarse implementation, if someone can provide a better alternative

String request = "POST /reverse HTTP/1.1\r\n" +
                        "Upgrade: PTTH/1.0\r\n" +
                        "Connection: Upgrade\r\n" +
                        "\r\n";

Socket socket = null;
try {
    socket = client.socketFactory().createSocket(ip, port);

    final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    // send the reverse http request
    out.write(request);
    out.flush();

    // read the reverse http response
    String reverseResponse = readResponse(in);

    if (!reverseResponse.trim().startsWith("HTTP/1.1 101 Switching Protocols")) {
        throw new IOException("can't setup reverse connection");
    }

    while (!stopped) {
        String eventData = readResponse(in);

            out.write("HTTP/1.1 200 OK\r\n" +
                        "Content- Length: 0\r\n\" + " +
                        "\r\n");
            out.flush();
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (socket != null) {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Trivia: Coincidentally, there is a different guy who drafted a similar solution and coincidentally named it reverse-http as well. This spec has a Reference Java Implementation , but not useful to you, since you are in no control of the server side.

On track :

I could find a Javascript implementation for the reverse-http that you are interested in here . Take a look for implementation hints, but, I guess you already have details.

For your problem, you would need a code fragment that can handle http requests (an http server functionality), while being embedded in a http client library.

Using Okhttp (I hope you are referring this ) to achieve what you want may be a bit of work. It provides Websocket support, which is a more evolved version of reverse-http. So, you may try customizing the Websocket implementation of okhttp for your case.

A simplistic solution like yours, where you need not parse the http response can be achieved by adapting the code of popular NanoHTTPD library. Latest releases have added more dependency but an older release has just 1 java file, with no dependency and ideal for such adaptations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM