1. 程式人生 > >使用HttpURLConnection呼叫簡訊介面

使用HttpURLConnection呼叫簡訊介面

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

/**
* @author   作        者:小杜
* @version  建立時間:2017-2-8 下午6:48:40 
* @Description 描述:傳送手機簡訊
*/
@Service
public class SendVerlifyCodeImpl implements ISendVerlifyCode {
	//傳送簡訊平臺的網址地址
	@Value("${sms.host}")
	private String host;
	//註冊傳送簡訊平臺的使用者名稱
	@Value("${sms.username}")
	private String username;
	//註冊傳送簡訊平臺的網址密碼
	@Value("${sms.password}")
	private String password;
	//註冊傳送簡訊平臺的網址的金鑰
	@Value("${sms.apikey}")
	private String apikey;

	/**
	 * 驗證碼的生成和傳送到手機
	 */
	@SuppressWarnings("unused")
	@Override
	public void SendVerlifyCode(String phoneNumber) {
		VerlifyCode vc = UserContext.getVerlifyCode();
		//1判斷是否能再次傳送簡訊,即當前session中沒有,或者時間間隔可以響應
		if (vc == null
				|| (vc != null && DateUtil.getSecondBetween(new Date(), vc.getSendDate()) >= BidConst.SEND_VERLIFY_CODE)) {
			//2如果能夠傳送
			//2.1生成一個驗證碼
			vc = new VerlifyCode();
			String code = UUID.randomUUID().toString().substring(0, 4);
			vc.setPhoneNumber(phoneNumber);
			vc.setSendDate(new Date());
			vc.setVerlifyCode(code);
			//2.2傳送簡訊
			String content = "傳送簡訊,你的驗證碼為" + code + "有效期為" + BidConst.VERLIFYCODE_VERLIFY_INTERVAL + "分鐘,請在在有效期內使用!";
			// 建立一個URL請求物件
			try {
				//使用HttpURLConnection來發送簡訊
				URL url = new URL(host);
				HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
				//設定請求方法為post,必須為大寫
				openConnection.setRequestMethod("POST");
				//設定為帶內容輸出
				openConnection.setDoOutput(true);
				//引數的拼接
				StringBuilder params = new StringBuilder().append("?username=" + this.username)
						.append("&password=" + this.password).append("&apikey=" + apikey).append("&content=" + content)
						.append("?phoneNumber=" + phoneNumber);
				//輸出引數
				openConnection.getOutputStream().write(params.toString().getBytes("UTF-8"));
				//連線 
				openConnection.connect();
				//得到響應的內容
				String responeText = StreamUtils
						.copyToString(openConnection.getInputStream(), Charset.forName("UTF-8"));
				if (responeText.startsWith("success")) {
					//2.3儲存相關資訊(傳送時間、電話號碼,驗證碼)可以放到session中去,傳送簡訊成功再儲存,否則 簡訊可以沒有傳送成功
					UserContext.putVerlifyCode(vc);
				} else {
					throw new RuntimeException("傳送失敗!");
				}
			} catch (Exception e) {
				throw new RuntimeException("傳送失敗!");
			}

		} else {
			throw new RuntimeException("你的驗證碼傳送過於頻繁!");
		}
	}
}

3.注意事項