基于http 和 https的文件下载

1.基于http下载

         //url为文件在服务器上的详细路径
        URL url = new URL("brook.com\Plugin_ngCUTE.xlsm");
        本地路径
        File dist = new File("D:\\Plugin_ngCUTE.xlsm");
        FileUtils.copyFile(url.openStream(), dist);

public class FileUtils{
    public static final void copyFile(final InputStream in, final File dst) throws IOException
    {
        final OutputStream out = new FileOutputStream(dst);
        copyFile(in, out);
    }
        public static void copyFile(final InputStream in, final OutputStream out)
            throws IOException {
        final byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
        {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

}

2.https

public static void downloadFile(String url, String path, String fileName) throws Exception {
        log.debug("path:" + path);
        log.debug("url:" + url);

        HttpClient client = null;
        try {
            client = getHttpClient();

            HttpGet httpGet = getHttpGet(url, null, null);
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] result = EntityUtils.toByteArray(response.getEntity());
                BufferedOutputStream bw = null;
                try {
                    File f = new File(path + "/" + fileName);
                    if (!f.getParentFile().exists())
                        f.getParentFile().mkdirs();
                    bw = new BufferedOutputStream(new FileOutputStream(f));
                    bw.write(result);
                } catch (IOException e) {
                    log.error("Error saving file,path=" + path + ",url=" + url, e);
                    throw e;
                } finally {
                    if (bw != null)
                        bw.close();
                }
            }
            else {
                StringBuffer errorMsg = new StringBuffer();
                errorMsg.append("httpStatus:");
                errorMsg.append(response.getStatusLine().getStatusCode());
                errorMsg.append(response.getStatusLine().getReasonPhrase());
                errorMsg.append(", Header: ");
                Header[] headers = response.getAllHeaders();
                for (Header header : headers) {
                    errorMsg.append(header.getName());
                    errorMsg.append(":");
                    errorMsg.append(header.getValue());
                }
                log.error("HttpResonse Error:" + errorMsg);
                throw new HttpResponseException("HttpResonse Error:" + errorMsg);
            }
        } catch (ClientProtocolException e) {
            log.error("Download the files saved to the local,http Connection exception,path=" + path + ",url=" + url, e);
            throw e;
        } catch (IOException e) {






            log.error("Download the files saved to the local,File operations abnormal,path=" + path + ",url=" + url, e);
            throw e;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
public static HttpClient getHttpClient() throws Exception{
        HttpClient httpclient = null;


        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("SSL");


        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme(getProperties().getProperty(TYPE), new Integer(getProperties().getProperty(PORT)) , sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);

        // apache HttpClient version >4.2 should use
        // BasicClientConnectionManager
        ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
        httpclient = new DefaultHttpClient(cm);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw e;
        }
        return httpclient;

    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值