package cn.base.util;

import java.io.BufferedReader;  
import java.io.IOException;
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;  
import java.net.HttpURLConnection;  
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL; 
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HttpRequestUtil {
	private static Logger iLog = Logger.getLogger(HttpRequestUtil.class);
	
	static boolean proxySet = false;
    static String proxyHost = "192.168.18.249";
    static int proxyPort = 8081;
    
    /** 
     * 编码 
     * @param source 
     * @return 
     */ 
    public static String urlEncode(String source,String encode) {  
        String result = source;  
        try {  
            result = java.net.URLEncoder.encode(source,encode);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
            return "0";  
        }  
        return result;  
    }
    public static String urlEncodeGBK(String source) {  
        String result = source;  
        try {  
            result = java.net.URLEncoder.encode(source,"GBK");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
            return "0";  
        }  
        return result;  
    }
    
    /**
     * 有参指向指定 URL 发送POST/GET方法的请求
     * 
     * @param url
     * 				发送请求的 URL
     * @param RequestMethod
     * 				请求方式 : POST/GET
     * @param param
     * 				请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param isproxy
     * 				是否使用代理模式
     * @param ContentType
     * 				 http传递类型 : JSON/HTTP     
     * @return 所代表远程资源的响应结果
     */
    public static String HttpSend(String url, String RequestMethod,String param, boolean isproxy, String ContentType) {
    	OutputStreamWriter out = null;
        BufferedReader in = null;
        URL realUrl=null;
        String result = "";
        
        try {
        	if("post".equals(RequestMethod.toLowerCase())){
        		realUrl = new URL(url);
        	}else{
        		String urlNameString="";
        		if(param!=null&&!("".equals(param))){
        			urlNameString = url + "?" + param;
        		}else{
        			urlNameString = url;
        		}
        		
        		realUrl = new URL(urlNameString);
        	}
            
            HttpURLConnection conn = null;
            if(isproxy){//使用代理模式
//                @SuppressWarnings("static-access")
//                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
//                conn = (HttpURLConnection) realUrl.openConnection(proxy);
            }else{
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 打开和URL之间的连接
             
            if("post".equals(RequestMethod.toLowerCase())){
            	 // 发送POST请求必须设置如下两行
            	if(param!=null&&!("".equals(param))){
            		conn.setDoOutput(true);
            	}else{
            		conn.setDoOutput(false);
            	}
                conn.setDoInput(true);
            }
            conn.setDefaultUseCaches(false);
            conn.setRequestMethod(RequestMethod);    // POST/GET方法
            // 设置通用的请求属性
             
            //conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "GBK,utf-8");
           //conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            
            if("json".equals(ContentType.toLowerCase())){
            	conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            }else{
            	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
            
            if("post".equals(RequestMethod.toLowerCase())){
            	if(param!=null&&!("".equals(param))){
            		conn.connect();
            		
            		// 获取URLConnection对象对应的输出流
                    out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
                    // 发送请求参数
                    out.write(param);
                    // flush输出流的缓冲
                    out.flush();
                    
                    
            	}
            	
           }
            
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            iLog.debug("***********result********** "+result);
            
        } catch (Exception e) {
        	iLog.debug("***********error********** "+e);
            e.printStackTrace();
            
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
                
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        
        return result;
        
    }
    
    public static void main(String[] args) {
//        String url = "http://10.123.6.97:7080/api/webapp/smssend?objtype=smssend";
    	
//        String url = "http://202.96.109.105:9000/tms/bycleInfoAction!getPlatenoInfo.do";
//        JSONObject postinfo = new JSONObject();
//        postinfo.put("UserID", "tzrfid");
//        postinfo.put("AppUserID", "test");
//        postinfo.put("AppUserName", "test");
//        postinfo.put("AppUserOrgname", "test");
//        postinfo.put("AppClinetIP", "10.123.6.48");
//        postinfo.put("MsgContent", "测试短信");
//        postinfo.put("TelNumber", "15268512379");
//        System.out.println(postinfo);
//        String result=HttpRequestUtil.HttpSend(url, "POST",postinfo.toString(), false, "JSON");
//        System.out.println(result);
        
        
//        String re="{\"rscode\":1,\"successcount\":1,\"failurecount\":0,\"rsmsg\":\"aaaa\"}";
//        JSONObject jsonobject = JSONObject.fromObject(re);
//        
//        Map<String,Object> mapListJson = JSONObject.fromObject(jsonobject);  
//        System.out.println(mapListJson.get("rscode"));
//		if("1".equals(String.valueOf(mapListJson.get("rscode")))){//发送成功
//			System.out.println("1111111111111111111111");
//		}else{
//			
//		}
		
    	
//    	 String url = "https://10.120.193.12/hnbk/szzs.aspx";
//    	 String infoString="fs=out&url=10.120.193.63";
    	
    	 
    	 String url = "http://172.16.66.43:8080/VIID/employee"; 
    	 String infoString = "id=10";
    	 String result=HttpRequestUtil.HttpSend(url, "GET", infoString, false, "HTTP");
    	 System.out.println(result);
    	 
        
    }
    
}
