package nc.util.fa.httputil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import nc.vo.pub.BusinessException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import com.alibaba.fastjson.JSONObject;

public class BillHttpRequestUtil {
	
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
    
     * @return 所代表远程资源的响应结果
	 * @throws BusinessException 
     */
    public static String sendPost(String postUrl, String postData) throws BusinessException {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new BusinessException("connect failed!");
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
        	 e.printStackTrace(System.out);
        	 throw new BusinessException(e.getMessage());
        }
    }
	
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            
            //绕过https证书校验
            if("https".equalsIgnoreCase(realUrl.getProtocol())){
            	SslUtils.ignoreSsl();
            }
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(120000);
            connection.setReadTimeout(120000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    /**
     * 向指定 URL 发送 x-www-form-urlencoded 参数格式 POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
    
     * @return 所代表远程资源的响应结果
     */
    public static String sendFormPost(String postUrl, JSONObject postData) {
    	
    	String result = "";
    	try {
    		    PostMethod postMethod = null;
    		    postMethod = new PostMethod(postUrl) ;
    		    postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
    		    //参数设置，需要注意的就是里边不能传NULL，要传空字符串
    		    NameValuePair[] data = {
    		            new NameValuePair("version",postData.getString("version")),
    		            new NameValuePair("appid",postData.getString("appid")),
    		            new NameValuePair("timestamp",postData.getString("timestamp")),
    		            new NameValuePair("sign",postData.getString("sign")),
    		            new NameValuePair("data",postData.getString("data")),
    		            new NameValuePair("format",postData.getString("format")),
    		            new NameValuePair("token",postData.getString("token"))
    		    };
    		    postMethod.setRequestBody(data);
    		    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
    		    httpClient.executeMethod(postMethod); // 执行POST方法
    		    result = postMethod.getResponseBodyAsString();
    		} catch (Exception e) {
    			e.printStackTrace();
    			result = "{\"code\":\"100\",\"msg\":\"NC调用接口失败: " + e.getMessage()+"\"}";
    		}
    	return result;
    }
    
    /**
     * 加传请求头信息参数值的POST请求
     * @param postUrl URL地址
     * @param postData json数据字符串
     * @param HeaderMap 请求头信息参数值Map
     * @return
     * @author czj 2020年6月7日 12:24:16
     */
    public static String sendPostByHeader(String postUrl, String postData, Map<String,String> HeaderMap) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            
            //请求头信息参数值
            if(null!=HeaderMap && !HeaderMap.isEmpty()){
            	for (String key : HeaderMap.keySet()) {
                    conn.setRequestProperty(key, HeaderMap.get(key));
                }
            }
            
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("connect failed!");
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
        	 e.printStackTrace(System.out);
        	 throw new RuntimeException(e.getMessage());
        }
    }
    
    /**
     * 主数据MDM系统专用POST请求
     * @param postUrl URL地址
     * @param postData json数据字符串
     * @param HeaderMap 请求头信息参数值Map
     * @return
     * @author czj 2020年12月29日 14:22:57
     */
    public static String sendMDMPostByHeader(String postUrl, String postData, Map<String,String> HeaderMap) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            
            //请求头信息参数值
            if(null!=HeaderMap && !HeaderMap.isEmpty()){
            	for (String key : HeaderMap.keySet()) {
                    conn.setRequestProperty(key, HeaderMap.get(key));
                }
            }
            
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(9000000);
            conn.setReadTimeout(9000000);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("connect failed!");
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
        	 e.printStackTrace(System.out);
        	 throw new RuntimeException(e.getMessage());
        }
    }

}