java - 怎么使用httpclient发送大文件(1G以上)
ringa_lee
ringa_lee 2017-04-18 10:48:54
0
4
679

怎么使用httpclient中的put方法上传大文件?
如果是一次性读到内存中发送的话,内存很容易撑爆,所以肯定是用边读边发的方式,或者使用分片上传。现在想知道怎么使用httpclient实现边读边传,使用jdk自带的方法已经知道怎么实现了。

    public static void putRequest(String uri, Map<String, String> headers, File file)
    {
        URLConnection urlconnection = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        
        try
        {
            URL url = new URL(uri);
            urlconnection = url.openConnection();
            urlconnection.setDoOutput(true);
            urlconnection.setDoInput(true);

            if (urlconnection instanceof HttpURLConnection)
            {
                try
                {
                    ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                    for(Map.Entry<String, String> entry : headers.entrySet())
                    {
                        ((HttpURLConnection) urlconnection).setRequestProperty(entry.getKey(), entry.getValue());
                    }
                    ((HttpURLConnection) urlconnection).connect();

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

            bos = new BufferedOutputStream(urlconnection.getOutputStream());
            bis = new BufferedInputStream(new FileInputStream(file));
            
            byte[] buff = new byte[1024 * 8];
            int i;
            while ((i = bis.read(buff)) != -1)
            {
                bos.write(buff, 0, i);
            }
            System.out.println(((HttpURLConnection) urlconnection).getResponseMessage());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(bos);
            ((HttpURLConnection) urlconnection).disconnect();
        }
    }
ringa_lee
ringa_lee

ringa_lee

Antworte allen(4)
大家讲道理

已经知道怎么传输了,关键是实现HttpEntity中的writeTo方法,httpclient中已经有了相关实现具体可以参考:

http://hc.apache.org/httpcomp...

    public void writeTo(final OutputStream outstream) throws IOException {
        Args.notNull(outstream, "Output stream");
        final InputStream instream = new FileInputStream(this.file);
        try {
            final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE];
            int l;
            while ((l = instream.read(tmp)) != -1) {
                outstream.write(tmp, 0, l);
            }
            outstream.flush();
        } finally {
            instream.close();
        }
    }

另外,这个FileEntity的实现用的是普通的IO方式,搜索可以知道,httpcore这个包已经实现了NFileEntity,采用的是FileChannel方式,会更高效

Peter_Zhu

可以用流的方式

伊谢尔伦

非要用http协议吗

伊谢尔伦

1G的大小就已经不建议通过http的方式来处理了。
ftp吧。

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage