问题:在WEB项目A中访问另一个WEB项目B,通过A向B中上传下载文件

上传:

       HttpPost httpPost = new HttpPost(upload_url);

       MultipartEntityBuilder builder = MultipartEntityBuilder.create();
           builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
       builder.addBinaryBody("file" , file, ContentType.MULTIPART_FORM_DATA, path);// 文件流
       builder.addTextBody("filename", path);// 类似浏览器表单提交,对应input的name和value
       HttpEntity entity = builder.build();

       httpPost.setEntity(entity);

       HttpResponse response = httpClient.execute(httpPost);// 执行提交

下载:

            String url = download_url + URLEncoder.encode(path, "UTF-8");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            entity = response.getEntity();

            InputStream in = entity.getContent();

  

注意点:

文件下载获取输入流后

1、直接调用 in.available() 时,返回为0。原因:网络通讯往往是间断性的,一串字节往往分几批进行发送

2、为解决上述问题,在调用 in.available() 前,先调用 in.read() 方法。使用该方法处理时,不能获取完整文件流

            int firstByte = inputStream.read();
            int length = inputStream.available();
            byte[] bytes = new byte[length+1];
            bytes[0] = (byte)firstByte;
            inputStream.read(bytes,1,length);
            inputStream.close();

3、该问题出现原因同样是因为网络文件流不稳定,解决方法是循环读取

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n=0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();

  

  

 

posted on 2021-09-16 16:14  啊哈咧  阅读(355)  评论(0编辑  收藏  举报