首页 > 编程语言 > 详细

Java后台远程下载url文件并远程上传文件

时间:2020-09-04 18:29:06      阅读:53      评论:0      收藏:0      [点我收藏+]

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 FilePart("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();
        }
    }

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 FilePart("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>

 

Java后台远程下载url文件并远程上传文件

原文:https://www.cnblogs.com/i-tao/p/13615143.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!