華爲雲-- 消息通知服務(SMN)

1:業務背景

利用華爲雲發送短信郵箱等消息

2:華爲雲設置

依次設置主題,訂閱(可爲手機號碼,郵箱地址),消息模板
在這裏插入圖片描述
消息模板變量可用{}格式,後臺填充數據:
在這裏插入圖片描述

3:代碼實踐

3.1:獲取token

官方文檔:https://support.huaweicloud.com/api-iam/zh-cn_topic_0057845583.html

https://iam.cn-east-2.myhuaweicloud.com/v3/auth/tokens
在這裏插入圖片描述
在這裏插入圖片描述
填充賬號密碼,以及projectid
在這裏插入圖片描述
如何獲取domain_name、project_name和project_id ?
https://support.huaweicloud.com/devg-sdk/zh-cn_topic_0070637164.html

HuaweiCloudUtil:

public static HttpResponse getToken(HuaweiCloudConfig config){
    String token = "";
    Gson gson = new Gson();
    TokenRequest request =  constructAuthRequest(config);
    String data  = gson.toJson(request);
    HttpResponse httpResponse = HttpReqUtil.postExecute(config.getAuthUrl(),data,null);
    httpResponse.setRequest(data);
    if(HttpResponse.RESPONSE_SUCCESS.equalsIgnoreCase(httpResponse.getResponseCode())){
        TokenResponse response = gson.fromJson(httpResponse.getResult(),TokenResponse.class);
        TokenConstant.expires_date = response.getToken().getExpires_at();
        Map<String,List<String>> headers = httpResponse.getHeader();
        for (String s : headers.keySet()) {
            if(TokenConstant.TOKEN_SUBJECT_KEY.equalsIgnoreCase(s)){
                token = headers.get(TokenConstant.TOKEN_SUBJECT_KEY).get(0);
                TokenConstant.TOKEN = token;
                break;
            }
        }
    }
    return httpResponse;
}

HttpReqUtil :

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import org.apache.commons.lang3.StringUtils;

public class HttpReqUtil {

	private static int DEFAULT_CONN_TIME = 5000;
	private static int DEFAULT_READ_TIME = 5000;
	
	public static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
	public static final String GET_METHOD = "GET";
	public static final String POST_METHOD = "POST";

    public static HttpResponse postExecute(String url, String data,Map<String,String> header) {
         return defaultConnection(POST_METHOD, url, data,header);
    }

	/**
	 * http request
	 * @param method GET/POST
	 * @param path  request url
	 * @param data
	 * @return
	 */
	private static HttpResponse defaultConnection(String method, String path, String data,Map<String,String> header){
        HttpResponse response = new HttpResponse();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(path);
            if (url != null) {
                conn = getConnection(method, url,header);
                conn.setConnectTimeout(DEFAULT_CONN_TIME);
                conn.setReadTimeout(DEFAULT_READ_TIME);
                if (StringUtils.isNoneBlank(data)) {
                    OutputStream output = conn.getOutputStream();
                    output.write(data.getBytes(DEFAULT_CHARACTER_ENCODING));
                    output.flush();
                }
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK || conn.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                    response.setHeader(conn.getHeaderFields());
                    InputStream input = conn.getInputStream();
                    String result = IOUtil.inputStreamToString(input, DEFAULT_CHARACTER_ENCODING);
                    response.setResult(result);
                }else{
                    InputStream input = conn.getErrorStream();
                    String error = IOUtil.inputStreamToString(input, DEFAULT_CHARACTER_ENCODING);
                    response.setError(error);
                }
                response.setResponseCode(HttpResponse.RESPONSE_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResponseCode(HttpResponse.RESPONSE_ERROR);
            response.setError(e.getMessage());
        }finally {
            if(conn!=null)
              conn.disconnect();
        }
        return response;

	}

	/**
	 * getConnection
	 */
	private static HttpURLConnection getConnection(String method, URL url,Map<String,String> header) throws IOException {
		HttpURLConnection conn = null;
		if ("https".equals(url.getProtocol())) {
			SSLContext context = null;
			try {
				context = SSLContext.getInstance("SSL", "SunJSSE");
				context.init(new KeyManager[0], new TrustManager[] { new MyX509TrustManager() },
						new java.security.SecureRandom());
			} catch (Exception e) {
				throw new IOException(e);
			}
			HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
			connHttps.setSSLSocketFactory(context.getSocketFactory());
			connHttps.setHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			});
			conn = connHttps;
		} else {
			conn = (HttpURLConnection) url.openConnection();
		}
		if(header!=null){
            for (String k : header.keySet()) {
                conn.setRequestProperty(k,header.get(k));
            }
        }
		conn.setRequestMethod(method);
		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		return conn;
	}

	public static String setParmas(Map<String, String> map, String path, String charset) throws Exception {
		String result = "";
		boolean hasParams = false;
		if (path != null && !"".equals(path)) {
			if (!map.isEmpty()) {
				StringBuilder builder = new StringBuilder();
				Set<Entry<String, String>> params = map.entrySet();
				for (Entry<String, String> entry : params) {
					String key = entry.getKey().trim();
					String value = entry.getValue().trim();
					if (hasParams) {
						builder.append("&");
					} else {
						hasParams = true;
					}
					if (charset != null && !"".equals(charset)) {
						builder.append(key).append("=").append(IOUtil.urlEncode(value, charset));
					} else {
						builder.append(key).append("=").append(value);
					}
				}
				result = builder.toString();
			}
		}
		return doUrlPath(path, result).toString();
	}

	private static URL doUrlPath(String path, String query) throws Exception {
		URL url = new URL(path);
		if (StringUtils.isEmpty(path)) {
			return url;
		}
		if (StringUtils.isEmpty(url.getQuery())) {
			if (path.endsWith("?")) {
				path += query;
			} else {
				path = path + "?" + query;
			}
		} else {
			if (path.endsWith("&")) {
				path += query;
			} else {
				path = path + "&" + query;
			}
		}
		return new URL(path);
	}
}
public class MyX509TrustManager implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

IOUtil :

public class IOUtil {
	
	/**
	 * description:convert InputStream to string
	 * @throws IOException
	 */
	public static String inputStreamToString(InputStream inputStream, String encoding) throws IOException {
		return IOUtils.toString(inputStream, encoding);
	}

	/**
	 * description: convert string to InputStream
	 * @throws IOException
	 */
	public static InputStream toInputStream(String inputStr, String encoding) throws IOException {
		if (StringUtils.isEmpty(inputStr)) {
			return null;
		}
		return IOUtils.toInputStream(inputStr, encoding);
	}
	

	/**
	 * description: encode URL
	 * @param source
	 * @param encode
	 * @return
	 */
	public static String urlEncode(String source, String encode) {
		String result = source;
		try {
			result = URLEncoder.encode(source, encode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
		return IOUtils.toByteArray(inputStream);
	}

}

再次忽略 pojo等

3.2:發送消息

URI格式

POST /v2/{project_id}/notifications/topics/{topic_urn}/publish
在這裏插入圖片描述

https://support.huaweicloud.com/usermanual-smn/smn_ug_0021.html

public static HttpResponse sendMessage(HuaweiCloudConfig config,MessageRequest messageRequest){
   Date now  = new Date();
    if(StringUtils.isBlank(TokenConstant.TOKEN)||TokenConstant.expires_date==null||now.after(TokenConstant.expires_date)){
        HttpResponse tokenResponse = getToken(config);
        if(!HttpResponse.RESPONSE_SUCCESS.equalsIgnoreCase(tokenResponse.getResponseCode())){
            return  tokenResponse;
        }
    }
    Gson gson = new Gson();
    String data  = gson.toJson(messageRequest);
    Map<String,String> header = new HashMap<>();
    header.put(TokenConstant.TOKEN_AUTH_KEY,TokenConstant.TOKEN);
    HttpResponse httpResponse = HttpReqUtil.postExecute(config.getSmnUrl(),data,header);
    httpResponse.setRequest(data);
    return httpResponse;
}
@Data
public class MessageRequest {

    private String subject;

    private String message_template_name;

    private Map<String,Object> tags = new HashMap<>();

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章