0
import aiohttp
import requests

listen_url = "https://somehttpstreamingurl"
headers = {"User-Agent": "stream client"}


async def async_listen():
    with aiohttp.ClientSession() as session:
        async with await session.get(url=listen_url, headers=headers) as r:
            while True:
                message = await r.content.readline()
                if message:
                    print(message)


def sync_listen():
    with requests.session() as session:
        r = session.send(requests.Request(method="GET", url=listen_url, headers=headers), stream=True)
        for message in r.iter_lines():
            if message:
                print(message)

So these are two examples of how we can get data from a http stream in Python (3.6 is the one I use)

However in Java I can't seem to do the same, and every google search I do I either get server sided streaming related results or file streaming uploads as results. I would like to write Java code equivalent to the Python code above, but http streaming searches are pretty cluttered when searching it for Java, and even worse when adding the "android" keyword to the search query. Does anyone know how to accomplish the Java eqivalent of the Python code above?

TMJnoob
  • 13
  • 3
  • You need a `Thread` object, a callback interface, and a `while` loop. What have you tried with this extend? Also, HTTP streaming on Android is just asking your battery to die – OneCricketeer Jan 05 '18 at 23:28
  • Maybe RxJava can help https://github.com/ReactiveX/RxApacheHttp#streaming-http-get-with-server-sent-events-textevent-stream-response – OneCricketeer Jan 05 '18 at 23:32
  • My api endpoint uses http streaming,however RxJava is looking very promising thanks – TMJnoob Jan 06 '18 at 16:40

1 Answers1

0

If you want to listen for incoming requests, first you need to read the message text and then do any parsing.

The Java Tutorial has a typical example:

There are also numerous questions in StackOverflow dealing with this use case, e.g.:

PNS
  • 17,431
  • 26
  • 86
  • 131
  • The question was asking about a continuous stream, though – OneCricketeer Jan 05 '18 at 23:30
  • That's what the BufferedReader in the Java Tutorial does: it continues reading, while there is data. – PNS Jan 05 '18 at 23:34
  • Thanks, I think the buffer reader should do, question though. In my case I am retrieving data from the stream to append to a listview, with that in mind woulld it be wiser to go with ths or the RxJava solution proposed in a comment on the question – TMJnoob Jan 06 '18 at 16:47
  • The general principle is that, if the "plain vanilla" solution does what is needed, it should be followed. In other words, play with it and you will figure it out. :-) – PNS Jan 07 '18 at 16:36
  • Aright, thanks this helpped a lot – TMJnoob Jan 07 '18 at 18:30
  • You are very welcome. :-) – PNS Jan 11 '18 at 21:43