Java接入253短信發送

短信發送主方法


package com.chuanglan.port;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
/**

* @param url 應用地址,類似於http://ip:port/msg/
* @param un 賬號
* @param pw 密碼
* @param phone 手機號碼,多個號碼使用","分割
* @param msg 短信內容
* @param rd 是否需要狀態報告,需要1,不需要0
* @return 返回值定義參見HTTP協議文檔
* @throws Exception
*/
public class HttpSender {
public static String batchSend(String url, String un, String pw, String phone, String msg,
String rd, String ex) throws Exception {
HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
GetMethod method = new GetMethod();
try {
URI base = new URI(url, false);
method.setURI(new URI(base, "send", false));
method.setQueryString(new NameValuePair[] { 
new NameValuePair("un", un),
new NameValuePair("pw", pw), 
new NameValuePair("phone", phone),
new NameValuePair("rd", rd), 
new NameValuePair("msg", msg),
new NameValuePair("ex", ex), 
});
int result = client.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return URLDecoder.decode(baos.toString(), "UTF-8");
} else {
throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
}
} finally {
method.releaseConnection();
}
}

}


信發送測試方法

import com.bcloud.msg.http.HttpSender;


public class HttpSenderTest {
public static void main(String[] args) {


String url = "http://sms.253.com/msg/";// 應用地址
String un = "詢問對接人";// 賬號
String pw = "a.123456";// 密碼
String phone = "18013108508";// 手機號碼,多個號碼使用","分割
String msg = "【253雲通訊】您好,你的驗證碼是123456";// 短信內容
String rd = 1;// 是否需要狀態報告,需要1,不需要0
String ex = null;// 擴展碼



try {
String returnString = HttpSender.batchSend(url, un, pw, phone, msg, rd, ex);
System.out.println(returnString);
// TODO 處理返回值,參見HTTP協議文檔
} catch (Exception e) {
// TODO 處理異常
e.printStackTrace();
}
}
}

所需jar包



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