【问题标题】:getContentLength returning 1225, real length 3365getContentLength 返回 1225,实际长度 3365
【发布时间】:2013-12-15 20:40:09
【问题描述】:

我目前正在使用 android,并且我正在使用带有一些标头的 http 连接(出于安全目的,我没有包含它们或真实的 url)从 API 获取 JSON 响应,并将该响应反馈回应用程序。我遇到的问题是,当使用 http 请求的 getContentLength 方法时,返回了错误的长度(返回的错误长度是 1225,JSON 数组的正确字符长度是 3365)。

我有一种感觉,当我的读者开始阅读 JSON 时,它并没有完全加载,因此那时只是在阅读加载的 JSON。有没有办法解决这个问题,可能使用 HTTP 连接延迟或等到它完全加载来读取数据?

            URL url = new URL("https://www.exampleofurl.com");
            HttpURLConnection request = (HttpURLConnection) url.openConnection();               

            request.connect();
            int responseCode = request.getResponseCode();   

            if(responseCode == HttpURLConnection.HTTP_OK) {

                InputStream inputStream = request.getInputStream();
                InputStreamReader reader = new InputStreamReader(inputStream);

                long contentLength2 = Long.parseLong(request.getHeaderField("Content-Length"));

                Log.i("contentLength: ", "Content: " + contentLength2);

【问题讨论】:

    标签: java android json https


    【解决方案1】:

    我通常不建议始终依赖“Content-Length”,因为它可能不可用(您得到 -1),或者可能受到中间代理的影响。

    你为什么不直接读取你的流,直到它被耗尽到内存缓冲区(比如,StringBuilder)然后得到实际大小,例如:

    BufferedReader br = new BufferedReader(inputStream); // inputStream in your code
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
        sb.append(line); 
    }
    // finished reading
    System.out.println("data size = " + sb.length());
    JSONObject data = new JSONObject(sb.toString());
    
    // and don't forget finally clauses with closing streams/connections
    

    【讨论】:

    • 先生,您是一位绅士和一位学者!完美运行!我试图投票给你,但它说我需要 15 名声望:/ 就像学校重新开始一样。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多