package com.trs.web2frame.tool.tyjyh.wcmhy02.si;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class HttpFileUpload {

	/** 
     * @param urlStr 
     * @param fileName 
     * @param savePath 
     * @throws IOException 
     */  
    @SuppressWarnings("unused")
	public static String  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
                //���ó�ʱ��Ϊ3��  
        conn.setConnectTimeout(3*1000);  

        //��ֹ���γ���ץȡ������403����  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  
        //�õ�������  
        try {
        	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("info:"+url+" download success");   
            return "1";
        }catch (Exception e) {
//        	Util.log("错误附件："+url,"附件不存在的路径",0);
        	System.out.println("附件不存在的路径！！");
        	return "2";
			// TODO: handle exception
		}
        
        
    }  
  
  
  
    /** 
               * ���������л�ȡ�ֽ����� 
     * @param inputStream 
     * @return 
     * @throws IOException 
     */  
    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();    
    }    
  
    /**
                 * ����������
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException { 
    	
    	 String aaa=downLoadFromUrl("http://192.141.7.59:8080/docs/huairou/fileDir/main/resource/cms/2016/11/img_pc_site/律师事务所合伙人变更备案流程图.jpg", 
    			 "20180589174文件.jpg","D:/");
    	 System.out.println(aaa);
//    	String url="http://219.232.207.30/mas/openapi/pages.do?method=download&appKey=gov&id=6";
//    	urlName(url);
//    	urlName1(url);
    }  
    
    
    public static void url(String url) throws IOException{
    	String filename = null;
    	URL myURL = new URL(url);
    	URLConnection conn = myURL.openConnection();
    	
    	conn.connect();
    	if(((HttpURLConnection) conn).getResponseCode()==200){
    		String file = conn.getURL().getFile();
    		filename = file.substring(file.lastIndexOf('/')+1);
    		System.out.println(filename);
//    		Log.v("111", filename);
    	}
    }
    
    public  String urlName(String url) throws IOException{
    	 String urlname=null;
    	 URLConnection conn;
         try {
             URL obj = new URL(url);
             conn = obj.openConnection();
             conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
             conn.setRequestProperty("Charset", "utf-8");
             Map<String, List<String>> map = conn.getHeaderFields();
//             Map<String, List<String>> map2 = conn.getRequestProperties();
             
             System.out.println("显示响应Header信息...\n");
             
             for (Map.Entry<String, List<String>> entry : map.entrySet()) {
//                 System.out.println("Key : " + entry.getKey() + 
//                         " ,Value : " + entry.getValue());
                 if("Content-Disposition".equals(entry.getKey())){
                	 String  name=entry.getValue().get(0);
                	 String[] spiltname=name.split(";");
                	 for(int a=0;a<spiltname.length;a++){
                		 String [] nname=spiltname[1].split("name=");
                		 for(int n=0;n<nname.length;n++){
                			 urlname=nname[1].substring(0, nname[1].lastIndexOf("."));
                		 }
                	 }
                 }
             }
             urlname=  URLDecoder.decode(urlname, "UTF-8");
             
//             System.out.println(urlname);
//           System.out.println("Authorization---->"+map.get("Authorization"));
//           System.out.println("\n使用key获得响应Header信息 \n");
             List<String> server = map.get("Server");
             if (server == null) {
                 System.out.println("Key 'Server' is not found!");
             } else {
                 for (String values : server) {
                     System.out.println(values);
                 }
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
         
         return urlname;
    }
    
    public static void urlName1(String url) throws IOException{

    	String suffixes="avi|mpeg|3gp|mp3|mp4|wav|jpeg|gif|jpg|png|apk|exe|pdf|rar|zip|docx|doc";
		Pattern pat=Pattern.compile("[\\w]+[\\.]("+suffixes+")");//正则判断
		Matcher mc=pat.matcher(url);//条件匹配
		while(mc.find()){
					String substring = mc.group();//截取文件名后缀名
					System.out.println(substring);

    }
		
		
    }
    
    private static String getFileName(Header Content) {
    	Header contentHeader = Content;
    	String filename = null;
    	if (contentHeader != null) {
    	HeaderElement[] values = contentHeader.getElements();
    		if (values.length == 1) {
    	NameValuePair param = values[0].getParameterByName("filename");
    		if (param != null) {
    			try {
    		    	//此处根据具体编码来设置
    		    	filename = new String(param.getValue().toString().getBytes("ISO-8859-1"), "GBK");
    		    	} catch (Exception e) { e.printStackTrace();}
    		}
    		}
    	}
		return filename;
    }
    
   
    
	/**
	 * 获取正文内资源
	 * List<String> list = new ArrayList<String>();
	 */
	public List<String>  getContentResource(String regExImg,int subStart,String content){
		List<String> list = new ArrayList<String>();
		Pattern patternImg = Pattern.compile(regExImg);
		Matcher matcherImg = patternImg.matcher(content);
		while (matcherImg.find()) {
			String picPath = matcherImg.group();
			picPath = picPath.substring(subStart, picPath.length());
//			String fullPath = getFullPath(picPath);
			System.out.println("匹配到的路径："+picPath);
			list.add(picPath);
		}
		List<String> remove=removeDuplicate(list);
		return remove;
	}
	/**
	 * 去除重复数据
	 */
	public static List<String> removeDuplicate(List<String> list) {   
	    HashSet<String> h = new HashSet<String>(list);   
	    list.clear();   
	    list.addAll(h);   
	    return list;   
	}

}
