/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:memberManageSys
 * File Name:MessageUtil.java
 * Package Name:ccpit.base.utils
 * Date:2016年1月19日上午8:44:55
 * Copyright (c) 2016, dingwei@ccpit.org All Rights Reserved.
 *
*/

package org.ccpit.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * ClassName:MessageUtil <br/>
 * Function: 发送短信测试类. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2016年1月19日 上午8:44:55 <br/>
 * @author   dingwei
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
public class MessageUtil {

	//发送短信路径接口  utf8编码
	/*private final static String MESSAGE_SMS_PATH = "http://utf8.sms.webchinese.cn/";
	private final static String REGISTER_COUNT = "信息中心2016"; //sms注册用户
	private final static String REGISTER_KEY = "d60ab6a7b099a1c9abf7"; //sms注册用户key
	private final static String TELPHONE = "15810468935,15116980323"; //手机号码
	private final static String SMSTEXT = "世界那么大，我想去看看"; //短信内容
	
	public static void main(String args[]){
		
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(MESSAGE_SMS_PATH);
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8"); //设置头文件转码
		NameValuePair[] data = {new NameValuePair("Uid", REGISTER_COUNT),new NameValuePair("Key", REGISTER_KEY),new NameValuePair("smsMob", TELPHONE),new NameValuePair("smsText", SMSTEXT)};
		postMethod.setRequestBody(data);
		
		try {
			client.executeMethod(postMethod);
			Header[] header = postMethod.getRequestHeaders();
			int statusCode = postMethod.getStatusCode();
			System.out.println("statusCode : "+statusCode);
			for(Header h : header){
				System.out.println(h.toString());
			}
			String result = new String(postMethod.getResponseBodyAsString().getBytes("utf8"));
			System.out.println(result); //打印返回消息状态
			postMethod.releaseConnection();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
	
	//查账户信息的http地址
    private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v1/user/get.json";

    //智能匹配模版发送接口的http地址
    private static String URI_SEND_SMS = "https://sms.yunpian.com/v1/sms/send.json";

    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v1/sms/tpl_send.json";

    //发送语音验证码接口的http地址
    private static String URI_SEND_VOICE = "https://voice.yunpian.com/v1/voice/send.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

   /* public static void main(String[] args) throws IOException, URISyntaxException {

        //修改为您的apikey.apikey可在官网（http://www.yuanpian.com)登录后获取
        String apikey = "8040506f5e745ebec2759efc6fb89e8a";

        //修改为您要发送的手机号
        String mobile = "15116980323";

        *//**************** 查账户信息调用示例 *****************//*
        System.out.println(MessageUtil.getUserInfo(apikey));

        *//**************** 使用智能匹配模版接口发短信(推荐) *****************//*
        //设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板）
        String text = "【中国国际商会】您的验证码是1234";
        //发短信调用示例
//        System.out.println(MessageUtil.sendSms(apikey, text, mobile));

        *//**************** 使用指定模板接口发短信(不推荐，建议使用智能匹配模版接口) *****************//*
        //设置模板ID，如使用1号模板:【#company#】您的验证码是#code#
        long tpl_id = 1;
        //设置对应的模板变量值

        String tpl_value = URLEncoder.encode("#code#",ENCODING) +"="
            + URLEncoder.encode("1234", ENCODING) + "&"
            + URLEncoder.encode("#company#",ENCODING) + "="
            + URLEncoder.encode("中国国际商会",ENCODING);
        //模板发送的调用示例
        System.out.println(tpl_value);
        System.out.println(MessageUtil.tplSendSms(apikey, tpl_id, tpl_value, mobile));

        *//**************** 使用接口发语音验证码 *****************//*
        String code = "1234";
        //System.out.println(JavaSmsApi.sendVoice(apikey, mobile ,code));
    }*/

    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws IOException
     */

    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        return post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模版接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String sendSms(String apikey, String text, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(URI_SEND_SMS, params);
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey    apikey
     * @param tpl_id    　模板id
     * @param tpl_value 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tpl_id));
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    /**
     * 通过接口发送语音验证码
     * @param apikey apikey
     * @param mobile 接收的手机号
     * @param code   验证码
     * @return
     */

    public static String sendVoice(String apikey, String mobile, String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("mobile", mobile);
        params.put("code", code);
        return post(URI_SEND_VOICE, params);
    }

    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
    
    public static void main(String[] args) throws IOException {
		//发送内容
		String content = "【中国国际商会】***活动将于2016年2月14日在北京举行，邀请您参加，我们的联系方式：010********"; 
		
		// 创建StringBuffer对象用来操作字符串
		StringBuffer sb = new StringBuffer("https://m.5c.com.cn/api/send/index.php?");
		
		// APIKEY 
		sb.append("apikey=7c319d7f6898ef8d50bad53fb2b9e808");

		//用户名 
		sb.append("&username=15116980323");

		// 向StringBuffer追加密码
		sb.append("&password=qwerfdsa123");

		// 向StringBuffer追加手机号码
		sb.append("&mobile=15116980323");

		// 向StringBuffer追加消息内容转URL标准码
		sb.append("&content="+URLEncoder.encode(content,"GBK"));

		// 创建url对象
		URL url = new URL(sb.toString());

		// 打开url连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		// 设置url请求方式 ‘get’ 或者 ‘post’
		connection.setRequestMethod("POST");

		// 发送
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

		// 返回发送结果
		String inputline = in.readLine();

		// 输出结果
		System.out.println(inputline);

	}
}

