@Component
public class SMSConnectorImpl implements SMSConnector {
final static Logger logger = LoggerFactory
.getLogger(SMSConnectorImpl.class);
RestTemplate restTemplate;
@Value("${sms.url}")
private String smsUrl;
@Value("${sms.accountid}")
private String smsAccountid;
@Value("${sms.password}")
private String smsPassword;
@Value("${sms.code}")
private String smsCode;
private String message;
public SMSConnectorImpl() {
restTemplate = new RestTemplate();
setConfig();
}
public boolean sendVerifyCode(String phone, String verifyCode) {
boolean result = false;
this.message = "account=" + smsAccountid + "&pwd=" + smsPassword
+ "&product=" + smsCode + "&mobile=$phone"
+ "&message=邻食验证码:$verifycode" + ",请在5分钟内按页面提示完成验证码校验【邻食】";
String sendMessage = message.replace("$phone", phone).replace(
"$verifycode", verifyCode);
logger.info(sendMessage);
Map<String, Object> urlVariables = new HashMap<String, Object>();
String response = restTemplate.postForObject(smsUrl, sendMessage,
String.class, urlVariables);
logger.info(response);
if (response != null && response.contains("200,"))
return true;
return result;
}
private void setConfig() {
ClientHttpRequestInterceptor acceptHeader = new AcceptHeaderHttpRequestInterceptor();
List<ClientHttpRequestInterceptor> list = new ArrayList<ClientHttpRequestInterceptor>();
list.add(acceptHeader);
restTemplate.setInterceptors(list);
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(
Charset.forName("GBK"));
restTemplate.getMessageConverters().set(1, stringHttpMessageConverter);
}
class AcceptHeaderHttpRequestInterceptor implements
ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
// List<MediaType> list = new ArrayList<MediaType>();
requestWrapper.getHeaders().setContentType(
MediaType.APPLICATION_FORM_URLENCODED);
requestWrapper.getHeaders().set("Accept-Charset", "utf-8");
return execution.execute(requestWrapper, body);
}
}