/**
* 发送短信
* @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);
URL url = null;
HttpURLConnection connection = null;
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;
* 发送短信
* @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"));
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"才会返回。