URLConnection下载文件,header中获取文件名称,模拟登录

private static void downfilewithname(String cookies,String urlString,String path) throws IOException {
		URL url = new URL(urlString);



		URLConnection con = url.openConnection();


		con.setRequestProperty("Cookie", cookies);


		String fieldValue = con.getHeaderField("Content-Disposition");





		String filename = fieldValue.substring(fieldValue.indexOf("fileName=") + 9, fieldValue.length() );


		File filetemp = new File(path);
		if(!filetemp.exists()){
			filetemp.mkdirs();
		}


		File download = new File(path, new String(filename.getBytes("ISO8859-1"),"gb2312"));
		if(download.exists()){ //如果文件存在,则不下载
			return;
		}



		ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());

		FileOutputStream fos = new FileOutputStream(download);

		try {
			fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

		} finally {
			fos.close();

		}
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的URLConnection和URL来下载文件,并且可以通过文件获取文件类型。以下是一个简单的示例代码: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class FileDownloader { public static void downloadFile(String fileUrl, String saveFilePath) throws Exception { URL url = new URL(fileUrl); URLConnection conn = url.openConnection(); InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(saveFilePath); byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("File downloaded successfully!"); // 获取文件类型 String contentType = conn.getContentType(); System.out.println("File type: " + contentType); } public static void main(String[] args) { String fileUrl = "https://example.com/sample.pdf"; String saveFilePath = "C:\\Downloads\\sample.pdf"; try { downloadFile(fileUrl, saveFilePath); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码,我们通过URL打开一个连接,然后获取输入流并将其写入文件输出流,最后关闭输入输出流。在下载完成后,我们使用`conn.getContentType()`方法获取文件类型。你只需要修改`fileUrl`和`saveFilePath`参数即可下载其他文件获取文件类型。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值