All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zhenzi.sms.ZhenziSmsClient Maven / Gradle / Ivy

package com.zhenzi.sms;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

public class ZhenziSmsClient {
	private static final String DEFAULT_CHARSET = "UTF-8";
//	private static final String url = "http://localhost:8080/zhenzisms";
//	private static final String url = "http://sms.zhenzikj.com";
	private String apiUrl = "";
	private static final int connectTimeout = 20 * 1000;
	private static final int readTimeout = 20 * 1000;
	private String appId;
	private String appSecret;

	public ZhenziSmsClient(String apiUrl, String appId, String appSecret) {
		this.apiUrl = apiUrl;
		this.appId = appId;
		this.appSecret = appSecret;
	}
	/**
     * 发送短信(需要状态回调)
     */
	public String send(Map params) throws Exception {
//        Map params = new HashMap();
//        params.put("appId", appId);
//        params.put("appSecret", appSecret);
//        params.put("message", message);
//        params.put("number", number);
//        params.put("messageId", messageId);
		params.put("appId", appId);
        params.put("appSecret", appSecret);
        String result = doPost(apiUrl+"/sms/v2/send.do", params, DEFAULT_CHARSET, connectTimeout,
        		readTimeout);
        return result;
	}
	/**
	 * 查询余额
	 */
	public String balance() throws Exception {
        Map params = new HashMap();
        params.put("appId", appId);
        params.put("appSecret", appSecret);
        String result = doPost(apiUrl+"/account/balance.do", params, DEFAULT_CHARSET, connectTimeout,
        		readTimeout);
        return result;
	}
	/**
	 * 查询短信
	 */
	public String findSmsByMessageId(String messageId) throws Exception {
        Map params = new HashMap();
        params.put("appId", appId);
        params.put("appSecret", appSecret);
        params.put("messageId", messageId);
        String result = doPost(apiUrl+"/smslog/findSmsByMessageId.do", params, DEFAULT_CHARSET, connectTimeout,
        		readTimeout);
        return result;
	}


	private String doPost(String url, Map params, String charset, int connectTimeout,
			int readTimeout) throws Exception {
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		String query = buildQuery(params, charset);
		byte[] content = new byte[0];
		if (query != null) {
			content = query.getBytes(charset);
		}
		HttpURLConnection conn = null;
		OutputStream out = null;
		String rsp = null;
		try {
			conn = getConnection(new URL(url), "POST", ctype, null);

			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(readTimeout);
			out = conn.getOutputStream();
			out.write(content);
			rsp = StreamUtil.read(conn.getInputStream(), DEFAULT_CHARSET);
		} finally {
			if (out != null) {
				out.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return rsp;
	}

	public String buildQuery(Map params, String charset) throws Exception {
		if ((params == null) || (params.isEmpty())) {
			return null;
		}
		StringBuilder query = new StringBuilder();
		Set> entries = params.entrySet();
		for (Map.Entry entry : entries) {
			String key = (String) entry.getKey();
			Object obj = entry.getValue();
			String value = null;
			if(obj != null && obj.getClass().isArray())
				value = JsonUtil.toJSONString((String[])obj);
			else
				value = obj.toString();
			query.append(
		            (URLEncoder.encode(key, charset)
		                + "="
		                + URLEncoder.encode(value, charset)
		                + "&"));
		}
		if(query.length() > 0)
			query.deleteCharAt(query.length()-1);
		return query.toString();
	}

	private HttpURLConnection getConnection(final URL url, String method, String ctype, Map headerMap)
			throws IOException, NoSuchAlgorithmException, KeyManagementException {
		String protocol = url.getProtocol();
		if(protocol.toLowerCase().equals("https")){//https协议
			SmsX509TrustManager xtm = new SmsX509TrustManager();//
	        SSLContext sslContext = null;
	        sslContext = SSLContext.getInstance("TLS");
            X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
            sslContext.init(null, xtmArray, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession sslSession) {
                	hostname = trim(hostname);
            		if(hostname.trim().equals("") || !url.getHost().equals(hostname))
            			return false;
                    return true;
                }
            });
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(method);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestProperty("Host", url.getHost());
		conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
		conn.setRequestProperty("Content-Type", ctype);
		if (headerMap != null) {
			for (Map.Entry entry : headerMap.entrySet()) {
				conn.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
			}
		}
		return conn;
	}
	private String trim(String s){
		if(s == null)
    		return "";
    	return s.trim();
	}
	/**
	 * 自定义证书管理器,信任所有证书
	 * @author pc
	 *
	 */
	public static class SmsX509TrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
		}
		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy