zoukankan      html  css  js  c++  java
  • Java后台远程下载url文件并远程上传文件

    1.远程下载url的二进制文件

    //获取二进制文件
    public static byte[]  downLoadBinary(String urlStr) throws IOException{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为10秒
            conn.setConnectTimeout(10*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
            //得到header
            Map<String, List<String>> map = conn.getHeaderFields();
            String fileName = map.get("Content-Disposition").get(0);
            fileName = fileName.substring(fileName.indexOf("=") + 1);
            System.out.println(fileName);
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取数据数组
            byte[] getData = readInputStream(inputStream);
            System.out.println(url + " download success");
            return getData;
        }
    //输入流转二进制
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    2.上传二进制文件到远程url

    public static void sendBinary(String toUrl,byte[] bytes,String fileName){
            PostMethod postMethod = new PostMethod(toUrl);
            BufferedReader br = null;
            try {
                //FilePart用来上传文件的类,file即要上传的文件
                //FilePart fp = new FilePart("file", file);
                FilePart fp = new CustomFilePart("file",new ByteArrayPartSource(fileName,bytes));
                Part[] parts = {fp};
    
                //对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
                MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
                postMethod.setRequestEntity(mre);
    
                HttpClient client = new HttpClient();
                //超时时间
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(postMethod);
                if (status == HttpStatus.SC_OK) {
                    System.out.println("发送成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                postMethod.releaseConnection();
            }
        }
    //重写FilePart导致中文文件名乱码
    public class CustomFilePart extends FilePart {
        public CustomFilePart(String filename, File file)
                throws FileNotFoundException {
            super(filename, file);
        }
        public CustomFilePart(String name, PartSource partSource) {
            super(name, (PartSource)partSource, (String)null, (String)null);
        }
        @Override
        protected void sendDispositionHeader(OutputStream out) throws IOException {
            super.sendDispositionHeader(out);
            String filename = getSource().getFileName();
            if (filename != null) {
                out.write(org.apache.commons.httpclient.util.EncodingUtil.getAsciiBytes(FILE_NAME));
                out.write(QUOTE_BYTES);
                //重写编码
                out.write(EncodingUtil.getBytes(filename, "utf-8"));
                out.write(QUOTE_BYTES);
            }
        }
    }

    3.依赖的httpclient

    <!--httpclient-->
        <dependency>
          <groupId>commons-httpclient</groupId>
          <artifactId>commons-httpclient</artifactId>
          <version>3.1</version>
       </dependency>

    1.远程下载url的文件

    public static void  downLoadFromUrl(String urlStr, String savePath) throws IOException{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为10秒
            conn.setConnectTimeout(10*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
            //得到返回的header
            Map<String, List<String>> map = conn.getHeaderFields();
            System.out.println(map);
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            //文件保存位置
            File saveDir = new File(savePath);
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            File file = new File(saveDir+File.separator+fileName);
            FileOutputStream fos = new FileOutputStream(file);
            //写入文件
            fos.write(getData);
            if(fos!=null){
                fos.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            System.out.println(url+" 下载成功");    

    2.上传文件

    public static void sendFile(String url, File file) {
            if (StringUtils.isBlank(url)) {
                throw new RuntimeException("url为空");
            }
            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }
            PostMethod postMethod = new PostMethod(url);
            BufferedReader br = null;
            try {
                //FilePart:用来上传文件的类,file即要上传的文件
                FilePart fp = new CustomFilePart("file", file);
                Part[] parts = {fp};
    
                //对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
                MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
                postMethod.setRequestEntity(mre);
    
                HttpClient client = new HttpClient();
                //超时时间
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(postMethod);
                if (status == HttpStatus.SC_OK) {
                    /*InputStream inputStream = postMethod.getResponseBodyAsStream();
                    br = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuffer stringBuffer = new StringBuffer();
                    String str = "";
                    while ((str = br.readLine()) != null) {
                        stringBuffer.append(str);
                    }*/
                    System.out.println("发送成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                postMethod.releaseConnection();
            }

    3.依赖的httpclient

    <!--httpclient-->
        <dependency>
          <groupId>commons-httpclient</groupId>
          <artifactId>commons-httpclient</artifactId>
          <version>3.1</version>
       </dependency>
  • 相关阅读:
    JMX示例
    在开发iOS程序时对日期处理的总结(转)
    iOS 身份证验证(转)
    IOS --- OC与Swift混编(转)
    Charles辅助调试接口(转)
    iOS 调试 crash breakpoint EXC_BAD_ACCESS SIGABRT(转)
    Objective-C中常量重复定义的解决方案
    layoutSubviews、drawRect、initialize和load方法的调用
    (转)iOS开发-常用第三方开源框架介绍(你了解的ios只是冰山一角)
    Mac OS10.10 openfire无法启动问题(转)
  • 原文地址:https://www.cnblogs.com/i-tao/p/13615143.html
Copyright © 2011-2022 走看看