I have a web URL which returns a JSON formatted string on request
{"StockID":0,"LastTradePriceOnly":"494.92","ChangePercent":"0.48"}
I'm streaming this using Java
InputStream in = null;
in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String result = sb.toString();
But reader.readLine()
is always returning null
Any idea what I'm doing wrong here?
Here is the actual JSON address http://app.myallies.com/api/quote/goog
UPDATE
Same code works OK on http://app.myallies.com/api/news, although both links have the same server implementation to generate the JSON response.
It looks like it was the User-Agent that it wanted. The following code works for me:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONTest {
public static void main(String[] args) throws Exception {
URL url = new URL("http://app.myallies.com/api/quote/goog");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0");
connection.setDoInput(true);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With