【问题标题】:Request Method GET returns wrong content length请求方法 GET 返回错误的内容长度
【发布时间】:2014-01-09 16:44:44
【问题描述】:

嗨,我正在使用 HttpURLConnection 获取 txt 文件的内容,我想知道该文件的大小,我使用内容长度方法,但它返回错误值,例如在此代码中文件的大小为17509 但它返回 5147 ? 所以有什么帮助吗? 提前非常感谢:)。

new Thread() {
                            @Override
                            public void run() {
                                String path = parser.getValue(e, "txt");
                                URL u = null;
                                try {
                                    u = new URL(path);
                                    HttpURLConnection c = (HttpURLConnection) u
                                            .openConnection();
                                    c.setRequestMethod("GET");
                                    c.connect();
                                    int lenghtOfFile = c.getContentLength();
                                    InputStream in = c.getInputStream();
                                    final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                                    byte[] buffer = new byte[1024];
                                    long total = 0;
                                    Log.i("p1",""+lenghtOfFile);
                                    while ((count = in.read(buffer)) != -1) {
                                        total += count;
                                        Log.i("p2",""+total);
                                        bo.write(buffer, 0, count);
                                    }
                                    bo.close();

                                } catch (MalformedURLException e) {
                                    e.printStackTrace();
                                } catch (ProtocolException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }
                        }.start();

【问题讨论】:

    标签: java android http connection


    【解决方案1】:

    内容长度是服务器设置的标头。我会检查以确保您的服务器返回正确的内容长度。你可以用 cUrl 做到这一点:

    curl -v http://path/to/file.txt
    

    这应该会显示发送和返回的标头。

    【讨论】:

    【解决方案2】:

    我能想到的一个快速解决方法就是忽略内容长度并读取输入流,直到没有任何内容可供读取。

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(8192);
    int read = inputStream.read();
    
    while (read != -1) {
       byteArrayOutputStream.write((byte) read);
       read = inputStream.read();
    }
    
    byteArrayOutputStream.flush();
    buf = byteArrayOutputStream.toByteArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多