java根据url下载文件出现301 Moved Permanently

1.问题原因
出现这种问题一般是由nginx重新定向导致的。
2.java代码解决方法
对nginx重新定向进行重新实例化url对象的操作,代码如下:

public static void main(String[] args) {
		
		String downLoadPath = "http://www.51ctc.com.cn/infFile/4b5c51fc43cdfe33a7fbcb03c630eb37.xlsx";
		String savePath = "d:/201907/2234.xlsx";
		
		fileLoad( downLoadPath, savePath);
		
		
	}
	
	/**
	 * 下载地址
	 * downLoadPath:下载地址
	 * savePath:保存的路径地址
	 * */
	public static void fileLoad(String downLoadPath,String savePath) {
		String urlName = downLoadPath;
		try {
	    	URL realUrl = new URL(downLoadPath);
	    	
	    	// 打开和URL之间的连接
	    	URLConnection conn = realUrl.openConnection();
	    	String newUrl = urlName;
	    	
	    	Map<String, List<String>> map = conn.getHeaderFields();
	    	 // 遍历所有的响应头字段
	        for (String key : map.keySet()) {
	        	 System.out.println(key + "--->" + map.get(key).get(0));
	        	if ("Location".equals(key)) {
	        		//获取新地址
	        		newUrl = map.get(key).get(0);
	        		 System.out.println("newUrl--->" +newUrl);
	        		break;
	        	}
	        }
	        // 重新实例化url对象
            realUrl = new URL(newUrl);
            // 重新打开和URL之间的连接
            conn = realUrl.openConnection();
	        
            // 建立实际的连接
            conn.connect();
            
            // 定义BufferedReader输入流来读取URL的响应
            InputStream inputStream = conn.getInputStream();
            
	        // 获取自己数组
	        byte[] getData = readInputStream(inputStream);
	        File file = new File(savePath);
	        FileOutputStream fos = new FileOutputStream(file);
	        fos.write(getData);
	        if (fos != null) {
	            fos.close();
	        }
	        if (inputStream != null) {
	            inputStream.close();
	        }			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
发布了24 篇原创文章 · 获赞 50 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u013015301/article/details/94740880
今日推荐