使用httpcomponents-client-4.3.5发短信

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class SendMsg_webchinese {

	public static final String UID = "123";
	public static final String KEY = "123456";
	public static final String SMS_SEND_URI = "http://utf8.sms.webchinese.cn";
	public static final String SMS_NUM_URI = "http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num";
	
	// 发送短信
	public static int sendMessage(String phone, String smsText) throws IOException{
		HttpPost post = new HttpPost(SMS_SEND_URI);
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("smsMob", phone));
		list.add(new BasicNameValuePair("smsText", smsText));
		String result = executeMethod(post, list);
		System.out.println("发送短信数量:" + result + ",手机号:" + phone + "信息:" + smsText);
		return Integer.parseInt(result);
	}
	
	// 获取短信数量
	public static int smsNum() throws IOException{
		HttpPost post = new HttpPost(SMS_NUM_URI);
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		String result = executeMethod(post, list);
		System.out.println("短信数量:" + result);
		return Integer.parseInt(result);
	}
	
	private static String executeMethod(HttpPost post, List<NameValuePair> list) throws IOException{
		list.add(new BasicNameValuePair("Uid", UID));
		list.add(new BasicNameValuePair("Key", KEY));
		post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse httpResponse = null;
		String result = "-1";
		try {
			httpResponse = httpClient.execute(post);
			Header[] headers = httpResponse.getAllHeaders();
			StatusLine statusLine = httpResponse.getStatusLine();
			System.out.println("statusLine:" + statusLine);
			for (Header h : headers) {
				System.out.println(h);
			}
			result = EntityUtils.toString(httpResponse.getEntity());
		} catch (IOException e) {
		} finally {
			post.releaseConnection();
			if(httpResponse != null) httpResponse.close();
			httpClient.close();
		}
		return result;
	}
}

由于官网提供的发短信为httpclient3.1版本,apache不再支持,改成apache最新版的httpclient

短信发送

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值