How can I solve this stream reading problem?

MHJ :

I am trying to read the response from an URL sending JSON body. But my code is not being able to read the complete response. There is a problem in my code but I am not getting that.

val url: URL = new URL("https://jsonplaceholder.typicode.com/todos/1")
val httpsConnection: HttpsURLConnection = url.openConnection().asInstanceOf[HttpsURLConnection]
httpsConnection.setRequestMethod("GET")
httpsConnection.setRequestProperty("Accept", "application/json")
httpsConnection.setRequestProperty("Accept-Language", "en_US")
val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream)
val bufferedReader = new BufferedReader(streamReader)
val stringBuffer: StringBuffer =new StringBuffer()
while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

println(stringBuffer.toString)

This above code is not giving me the actual result. But if I avoid the regular Java style and use scala source:

Source.fromInputStream(httpsConnection.getInputStream,"UTF8").getLines().foreach(println)

this gives the actual JSON.

What is the problem in my first section of codes?

Krzysztof Atłasik :

In this place:

while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

you're calling readLine twice first to check if it's not null, then to append to stringBuffer. But actually, the second call gets another line, so you're losing every second line.

The usual way to read buffered stream in Java is:

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}

but assignments in Scala returns Unit so it won't work.

So maybe using Stream.continually would be way to go?

Stream
    .continually(bufferedReader.readLine())
    .takeWhile(_ != null)
    .foreach(stringBuffer.append)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327757&siteId=1
Recommended