java读取网络资源文件(用于请求短信发送功能)

用java去读取网络资源一般需要使用到java.net这个包,这个包中的URL类用于指向网络资源,通过建立HttpUrlConnection对象和网络资源建立连接,通过方法getInputStream方法可以读取网络资源的内容,对于我的这个功能,在这里读取的是短信发送成功失败的状态吗,读取后建立inputStreamReader可以根据指定的格式将字节转换为字符,最后从字符流中读取文本的内容,释放网络资源饭后读取的内容



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class SmsBase {

	private static String uid = "nonononono";
	private static String pwd = "nonononono";
	private static final String msg = "您在蓝游请求的验证码是:";

	// x_eid企业代码,个人账号值为0
	// x_gate_id值为300.代表组合通道
	// x_target_no可以多个号码最多100个每次。之间用[,]分开。例如:15910011001,1591061000,15912341234
	// x_memo短信内容70字
	public static String SendSms(String mobile, String content)
			throws UnsupportedEncodingException {
		//申明一个URLConnection对象,用于建立与url所指向的远程对象的连接
		HttpURLConnection httpconn = null;
		String result = "-12";
		content = msg + content.trim();
		if (content.length() > 69) {
			return "-11";
		}
		// String us =
		// "http://service.winic.org/sys_port/gateway/?id="+uid+"&pwd="+pwd+"&to="+mobile+"&content="+URLEncoder.encode(content,"GB2312")+"&time=";
		//该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候
		StringBuilder sb = new StringBuilder();
		sb.append("http://service.winic.org/sys_port/gateway/?id=");
		sb.append(uid);
		sb.append("&pwd=").append(pwd);
		sb.append("&to=").append(mobile);
		sb.append("&content=").append(URLEncoder.encode(content, "GB2312"));
		sb.append("&time=");
		try {
			//类url代表一个统一资源定位服,相当于网络资源的指针
			URL url = new URL(sb.toString());
			//返回一个URLConnection对象,他表示到url所引用的资源的连接
			httpconn = (HttpURLConnection) url.openConnection();
			//从字符输入流中读取数据,缓冲各个字符,从而实现字符,数组和行的高效读取
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()));
			//读取一个文本行
			result = rd.readLine();
			rd.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpconn != null) {
				//指示近期服务器不太可能有其他请求。
				httpconn.disconnect();
				httpconn = null;
			}

		}
		return result;
	}

	/**
	 * @param args
	 * @throws UnsupportedEncodingException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		String r = SendSms("15000577371", "666");
		if(!r.startsWith("000")){
			//TODO 短信发送失败..
		}
		System.out.println(r);
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值