java - 来自 URL 的 JSON 序列化总是返回 NULL

标签 java android json serialization deserialization

我有一个 Web URL,它根据请求返回一个 JSON 格式的字符串

{"StockID":0,"LastTradePriceOnly":"494.92","ChangePercent":"0.48"}

我正在使用 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();

但是 reader.readLine() 总是返回 null

知道我在这里做错了什么吗?

这里是实际的JSON地址http://app.myallies.com/api/quote/goog

更新

相同的代码在 http://app.myallies.com/api/news 上运行正常,尽管这两个链接具有相同的服务器实现来生成 JSON 响应。

最佳答案

看起来它就是它想要的 User-Agent。以下代码对我有用:

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

    }

}

关于java - 来自 URL 的 JSON 序列化总是返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930218/

相关文章:

android - 如何减少android中的内存消耗

java - 位图大小超过 Vm 预算错误 android

json - 如何获取主键相关字段嵌套序列化程序 django rest 框架的所有值

php - 通过 PHP 脚本将 JSON 文件插入 MySQL

java - 将json字符串转换为java对象?

java - Jersey 2 - 获取客户端上的基本 URI

java - 使用 echo 命令将八进制字符串写为 ASCII 字符

java - 透明背景滚动文本

java - ListView 上所选项目的背景颜色没有改变?

android - 屏幕尺寸与按钮位置