JAVA接入中國網建SMS短息短信平臺開發(學習整理)

1、增加架包


		<!-- 中國網建提供的SMS短信 -->
		<dependency>
		    <groupId>commons-httpclient</groupId>
		    <artifactId>commons-httpclient</artifactId>
		    <version>3.1</version>
		</dependency>
		<dependency>
		    <groupId>commons-logging</groupId>
		    <artifactId>commons-logging</artifactId>
		    <version>1.1.1</version>
		</dependency>
		<dependency>
		    <groupId>commons-codec</groupId>
		    <artifactId>commons-codec</artifactId>
		    <version>1.4</version>
		</dependency>

2、具體代碼

package xk20190810.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class SendMsg {

	public static final String NAME = "qq19****2438";// "用 戶 名:"非登錄用戶名

	public static final String PWD = "d41************204e980";// "短信密鑰"

	public PostMethod sendMsg(String phone, Integer code) {

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
		post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在頭文件中設置轉碼
		NameValuePair[] data = { 
			new NameValuePair("Uid", NAME), 
			new NameValuePair("Key", PWD),
			new NameValuePair("smsMob", phone), 
			new NameValuePair("smsText", "您的驗證碼是:" + code + ",60秒內有效,如非本人操作請忽略。")
		};
		post.setRequestBody(data);
		try {
			client.executeMethod(post);
		} catch (Exception e) {
			System.out.println("短信發送異常" + e);
		}
		return post;
		
//		int statusCode = post.getStatusCode();//獲取發送短信請求是否成功結果
//		System.out.println("statusCode:" + statusCode);
//		Header[] headers = post.getResponseHeaders();//獲取請求頭信息
//		for (Header h : headers) {//遍歷頭部信息
//			System.out.println("h.Str:" + h.toString());
//		}
//		try {
//			String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
//			System.out.println("result:" + result);
//		} catch (Exception e) {
//			System.out.println("獲取結果異常" + e);
//		}
//		post.releaseConnection();//作用是重置request狀態位,爲下次使用做好準備。
		
	}
	
	public static void main(String[] args) {
		SendMsg sm = new SendMsg();
		PostMethod post = sm.sendMsg("15882095302", 19960203);
		Integer RequestResult = post.getStatusCode();//獲取發送短信請求是否成功
		try {
			String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
			System.out.println("發送短信請求結果:" + RequestResult);
			System.out.println("短信發送結果:" + result);
			post.releaseConnection();//作用是重置request狀態位,爲下次使用做好準備。
		} catch (Exception e) {
			System.out.println("獲取結果異常" + e);
		}
	}
}

 

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