https://twitter.com/jessewilson/status/692326663061966848
Original issue:
I'm struggling with reading from a BufferedSource twice. What I'm trying to do is take an okhttp response body and stream it to both a parser and a file. First I created 2 Bufferinstances from same BufferedSource next I wrap a Buffer in an InputStreamReader and gracefully (or so I thought) pass it to gson. What I get is MalformedJsonException
If I however simply do body.source().readUtf8Line() I get the full raw json.
full example:
Request request = new Request.Builder()
.url("https://www.reddit.com/r/aww/new/.json")
.build();
response =new OkHttpClient().newCall(request).execute();
ResponseBody body = response.body();
BufferedSource sourceforFile = body.source();
sourceforFile.require(8014);
Buffer buffer = sourceforFile.buffer();
Buffer sourceForParser = buffer.clone();
InputStreamReader inputStreamReader = new InputStreamReader(sourceForParser.inputStream());
result= new GsonBuilder()
.registerTypeAdapterFactory(new GsonAdaptersModel()).create()
.fromJson(inputStreamReader, RedditData.class);
File file = new File(getContext().getCacheDir(), "file");
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(sourceforFile.buffer());
diskValue = Okio.buffer(Okio.source(file)).readString(Charset.defaultCharset());
It seems like Buffers are perfectly suited for taking a single source and streaming in multiple direction, would love to finally bring it all together. Thank you for your help.
https://twitter.com/jessewilson/status/692326663061966848
Original issue:
I'm struggling with reading from a BufferedSource twice. What I'm trying to do is take an okhttp response body and stream it to both a parser and a file. First I created 2
Bufferinstances from sameBufferedSourcenext I wrap aBufferin anInputStreamReaderand gracefully (or so I thought) pass it to gson. What I get isMalformedJsonExceptionIf I however simply do
body.source().readUtf8Line()I get the full raw json.full example:
It seems like Buffers are perfectly suited for taking a single source and streaming in multiple direction, would love to finally bring it all together. Thank you for your help.