Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Serialisation from URL always returning NULL

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.

like image 862
Maya Avatar asked Oct 31 '22 11:10

Maya


1 Answers

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());

    }

}
like image 189
Jimmy James Avatar answered Nov 09 '22 13:11

Jimmy James