通过Https登录并下载文件

通过Https登录并下载文件。

1.必须是https方式连接。

2.解决Basic认证,即登录框的用户名密码填写操作。

 

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

/**
 * 通过Https登录并下载文件。<br>
 * 1.必须是https方式连接。<br>
 * 2.解决Basic认证,即登录框的用户名密码填写操作。
 * 
 * @author Concurrency 2012-12-19
 */
public class HttpsDownload {
	public static void main(String[] args) {
		// Https
		new HttpsDownload().downloadFile("https://where,is.it/download.zip", "D:/test/download.zip");
	}

	/**
	 * 
	 * @param httpsURL
	 *            httpsURL
	 * @param tempFile
	 *            temp file path
	 */
	private void downloadFile(String httpsURL, String tempFile) {
		HttpsURLConnection httpsCon = null;
		FileOutputStream fos = null;
		InputStream is = null;
		final int BUFFER_SIZE = 1024;
		try {
			// 为Basic认证加上用户名和密码并支持https
			Authenticator.setDefault(new AddBasicPasswordAndSSL());
			// 打开URL通道
			URL url = new URL(httpsURL);
			httpsCon = (HttpsURLConnection) url.openConnection();
			// 开始网络连接
			httpsCon.setConnectTimeout(2000);
			httpsCon.connect();
			// 读写的缓存
			byte[] buffer = new byte[BUFFER_SIZE];

			int size = 0;
			is = httpsCon.getInputStream();
			fos = new FileOutputStream(tempFile);
			// 开始读写文件
			while ((size = is.read(buffer)) != -1) {
				fos.write(buffer, 0, size);
				fos.flush();
			}
		} catch (Exception e) {
			//Exception handle
		} finally {
			close(is, fos, httpsCon);
		}
	}

	private void close(InputStream is, OutputStream os, HttpsURLConnection connection) {
		try {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
			if (connection != null) {
				connection.disconnect();
			}
		} catch (Exception e) {
			// nanimosinai
		}

	}

	/**
	 * 通过继承Authenticator类为Basic认证加上用户名密码 . 另外用于支持HttpsURLConnection连接
	 * 
	 */
	private class AddBasicPasswordAndSSL extends Authenticator {
		private final String username = "Administrator";
		private final String password = "123456789";

		AddBasicPasswordAndSSL() throws KeyManagementException, NoSuchAlgorithmException {
			MyX509TrustManager xtm = new MyX509TrustManager();
			MyHostnameVerifier hnv = new MyHostnameVerifier();
			SSLContext sslContext = null;
			sslContext = SSLContext.getInstance("TLS"); // 或SSL
			X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
			sslContext.init(null, xtmArray, new java.security.SecureRandom());

			if (sslContext != null) {
				HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
			}
			HttpsURLConnection.setDefaultHostnameVerifier(hnv);

		}

		// 为Basic认证加上用户名和密码
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password.toCharArray());
		}
	}

	/**
	 * 重写X509TrustManager的方法,用于支持https连接。但是并未对服务器的证书作验证,它就会信任任何证书。
	 * 
	 */
	private class MyX509TrustManager implements X509TrustManager {

		/*
		 * 该方法检查客户端的证书,若不信任该证书则抛出异常。
		 */
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) {

		}

		/*
		 * 该方法检查服务器的证书,若不信任该证书同样抛出异常。通过自己实现该方法,可以使之信任我们指定的任何证书。在实现该方法时,
		 * 也可以简单的不做任何处理, 即一个空的函数体,由于不会抛出异常,它就会信任任何证书。
		 */
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) {

		}

		/*
		 * 返回受信任的X509证书数组。
		 */
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;

		}

	}

	/**
	 * hostname verification
	 * 
	 */
	private class MyHostnameVerifier implements HostnameVerifier {

		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
}
 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用C#的FtpWebRequest类来实现FTP匿名登录下载文件。下面是一个示例代码: ```csharp using System; using System.IO; using System.Net; class Program { static void Main(string[] args) { string ftpUrl = "ftp://example.com/file.txt"; string localPath = "C:\\local\\file.txt"; try { // 创建FTP请求对象 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential("anonymous", ""); // 获取FTP服务器的响应 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // 打开本地文件流 using (Stream stream = response.GetResponseStream()) { // 创建本地文件 using (FileStream fileStream = new FileStream(localPath, FileMode.Create)) { byte[] buffer = new byte[1024]; int bytesRead = 0; // 从FTP服务器读取数据,并写入本地文件 while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } } } Console.WriteLine("文件下载成功!"); } catch (Exception ex) { Console.WriteLine("文件下载失败: " + ex.Message); } } } ``` 请将示例代码中的 `ftp://example.com/file.txt` 替换为实际的FTP服务器地址和文件路径,将 `C:\\local\\file.txt` 替换为本地保存文件的路径和文件名。这段代码会使用匿名登录凭据从FTP服务器下载文件,并将其保存到本地路径中。 注意:匿名登录是通过提供 "anonymous" 作为用户名和空字符串作为密码来实现的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值