package com.util;
/**
 * @author 作者姓名: dubaohui
 * @version 创建时间：2015-9-18 上午11:31:04
 * 类说明
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

 
import net.sf.json.JSONObject;
 
/**
*短信API服务调用示例代码 － 聚合数据
*在线接口文档：http://www.juhe.cn/docs/54
**/
 
public class OutCall {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    public static String url ="http://121.40.120.141/app";
 
    //2.外呼
    public static boolean getTalk(String phoneno,String zxno,String key){
    	boolean sign = false;
        String result =null;
        Map<String, Object> params = new HashMap<String, Object>();//请求参数
            params.put("Action","Dialout");//命令名称，外呼接口中固定名称为Dialout
            params.put("ActionID",key);//随机码，用户用来标识请求的操作，服务器返回的Response中会带有对应Action的ActionID；在通话事件中会带有该字段；该字段最大长度是40个字节
            params.put("Account","N00000002010");
            params.put("Exten",phoneno);//被叫号码
            params.put("FromExten",zxno);//坐席工号
            params.put("PBX", "sh.ali.1.5");
            params.put("ExtenType", "gateway");//外呼时强制座席使用该接听方式。可选参数。正常情况下调用外呼接口不需传此字段，座席默认使用登陆呼叫中心的接听方式外呼。
            //如有特殊需要，例如：座席不登陆系统发起外呼，需要传此字段。
            //Local为“手机”
            //sip为“软电话”
            //gateway为“语音网关”
 
        try {
            result =net(url, params, "GET");
            System.out.println("---"+result);
            JSONObject object = JSONObject.fromObject(result);
            sign = object.getBoolean("Succeed");
        } catch (Exception e) {
            e.printStackTrace();
            sign = false;
        }
        return sign;
    }
 
 
 
    public static void main(String[] args) {
    	System.out.println(getTalk("13764935808","8003",RequestUtil.getid(6)));
    	
    }
 
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, final Map<String, Object> params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
//            String last = strUrl.substring(strUrl.length()-1, strUrl.length());
//            if("&".equals(last)){
//            	strUrl = strUrl.substring(0, strUrl.length()-1);
//            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
//            if (params!= null && method.equals("POST")) {
//            	try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
//                    out.writeBytes(urlencode(params));
//                }
//            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
