发送短信

/**
* 发送短信
* @param phone  手机号码
* @param content 发送内容
*/
private static boolean send( String phone, String content ) throws Exception {

1、拼接 URL 路径
StringBuffer sb = new StringBuffer( "http://xxx/xxx/" );   
sb.append( "id=xxx" );
sb.append( "&pwd=xxx" );
sb.append("&phone="+phone);

sb.append("&content=" + URLEncoder.encode(content,"gbk"));


BufferedReader in = null;
URL url = null;
HttpURLConnection connection = null;

int result = 0;

2、打开 URL 链接并设置 

try {
url = new URL(sb.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
in = new BufferedReader(new InputStreamReader(url.openStream()));
result = Integer.parseInt(in.readLine());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (connection != null) {
connection.disconnect();
}
}
return result == 100;

}



注:

url.openConnection()   打开链接,一旦你的连接成功,你就可以开始对这个 URLConnection 的输入以及输出流进行读和写的操作。

connection.setRequestMethod("POST");   连接设置

url.openStream();打开一个通道

in.readLine();  而实际上readLine()是一个阻塞函数,当没有数据读取时,就一直会阻塞在那,而不是返回null;

     readLine() 只有在数据流发生异常或者另一端被close() 掉时,才会返回 null 值。

          如果不指定 buffer 大小,则 readLine() 使用的 buffer 有8192个字符。在达到 buffer 大小之前,只有遇     到"/r"、"/n"、"/r/n"才会返回。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值