请教关于http的post方法

3 views
Skip to first unread message

wang hongjiang

unread,
Sep 10, 2008, 8:42:38 AM9/10/08
to dev4s...@googlegroups.com
遇到这样的现象:通过浏览器上传一个大文件时(300多m)没有问题。但用java程序连接服务器发送该文件数据就会出错。
用浏览器上传文件时,也是通过 HTTP的 post方式执行的吧?

请看下面的 Java代码,程序会报java.lang.OutOfMemoryError
我不确定是java的bug(我用的是1.6的版本),还是确实和http协议的特征有关,比如它只允许每次post 4m的数据(具体应该和http server相关)?
个人感觉浏览器也是用这种方式上传文件的,有明白的人请讲解一下。

public static void main(String[] args) {
        try {
            String jsp = "/test/test.jsp?act=upload";
            URL url = new URL("http", "localhost", 8080, jsp);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/x-www-form-urlencode");
            conn.setDoOutput(true);

            //
            String f = "E:\\Movie\\兄弟连\\01.rmvb";
            BufferedInputStream bufIs = new BufferedInputStream(new FileInputStream(f));
            BufferedOutputStream bufOs = new BufferedOutputStream(conn.getOutputStream());
           
            byte[] buf = new byte[1024 * 16];
            int len = 0;
            int c = 0;
            while((len = bufIs.read(buf)) > 0){
                System.out.println(c++); // 执行第2048次时(32M)报java.lang.OutOfMemoryError: Java heap space
                bufOs.write(buf, 0, len);
                bufOs.flush(); // 看起来没有真正工作?
            }
   
            bufIs.close();
            bufOs.close();
           
            System.out.println("ok!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

--
room113

Lei Gu

unread,
Sep 10, 2008, 10:34:36 AM9/10/08
to dev4s...@googlegroups.com
循环里强制调用一下GC

2008/9/10 wang hongjiang <w.hon...@gmail.com>

sun baoming

unread,
Sep 10, 2008, 10:44:06 AM9/10/08
to dev4s...@googlegroups.com
不一定是客户端的问题,因为你是连本机服务端,服务端的程序也可能会把内存用光。

是每次到32M时都报错,还是只是偶尔。

2008/9/10 Lei Gu <jack...@gmail.com>

Ray York

unread,
Sep 10, 2008, 11:12:51 AM9/10/08
to dev4s...@googlegroups.com
一下读那么多数据应该不需要用BufferedInputStream吧,有没有可能读缓冲区持续膨胀?

room113

unread,
Sep 10, 2008, 8:41:28 PM9/10/08
to 高性能网络编程邮件列表
OK,找到问题所在了。
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5026745
里面提到:
---------------------------
OK, I have to admit that it works in 1.5.0-b64.
But not the way described above.
You have to use HttpURLConnection.setChunkedStreamingMode(len).
---------------------------
需要设定每次发送数据的大小,否则它将按照默认的缓冲大小4k
而我使用的缓冲是 16K, 所以设定 conn.setChunkedStreamingMode(1024 * 16). 就没有问题了。


On 9月10日, 下午11时12分, Ray York <rayor...@gmail.com> wrote:
> 一下读那么多数据应该不需要用BufferedInputStream吧,有没有可能读缓冲区持续膨胀?-------- Original Message --------
> Subject: 请教关于http的post方法
> From: wang hongjiang<w.hon...@gmail.com>
> To:dev4s...@googlegroups.com
> Date: 2008-9-10 20:42遇到这样的现象:通过浏览器上传一个大文件时(300多m)没有问题。但用java程序连接服务器发送该文件数据就会出错。
Reply all
Reply to author
Forward
0 new messages