java调用短信接口使用实例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SMSUtils {

	private static String corpid = "xxx";// 用户
	private static String pswd = "xxx";// 密码
	private static String loginParam = "?corpid=" + corpid + "&pswd=" + pswd;
	private static int timeOut = 20000;//超时

	/**
	 * 发送单条短信
	 */
	public static String sendGet(String phone, String msg) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
		String timeStr = sdf.format(new Date());// 当前的时间戳
		BufferedReader in = null;

		StringBuilder http = new StringBuilder();
		http.append("http://120.31.132.210/httpinterface/mt.php");
		http.append(loginParam);
		http.append("&smsid=");
		http.append(phone);
		http.append(timeStr);
		http.append("&mob=");
		http.append(phone);
		http.append("&msg=");
		http.append(msg);

		String codeStr = "";// 存放返回值的代码
		try {
			URL realUrl = new URL(http.toString());
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性

			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
			"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setReadTimeout(timeOut);
			// 建立实际的连接
			connection.connect();
			
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                
			String line;
			while ((line = in.readLine()) != null) {
				codeStr += line;
			}

		} catch (IOException io) {
			System.out.println("发送GET请求出现异常!" + io);
			io.printStackTrace();
		}

		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return codeStr;
	}

	public static void main(String[] args) {

		String mob = "电话号码";
		String msg = "短信内容";// 短信的内容
		System.out.println("短信号码:" + mob);
		String response = sendGet(mob, msg);
		System.out.println("返回的验证码:" + response);

	}

}


你可能感兴趣的:(java调用短信接口使用实例)