java爬虫获取天气信息并发送短信。

java爬虫获取天气信息并发送短信:

   自己谷脑java获取网页信息,想着顺便发送短信给自己实现一个天气短信提醒的小玩意。可加入自己项目中,做个定时任务。完善这个小玩意。:

   需要SMS平台的注册。获取到key;可自己查看SMS短信发送平台,恶心的就是  免费的只有5条短信。仅供自己娱乐。

    所需jar

 

    org.apache.httpcomponents
    httpclient
    4.5.2

   

    org.jsoup
    jsoup
    1.10.2

   

    commons-httpclient
    commons-httpclient
    3.1

public class Test {
	public static void main(String[] args) throws Exception {
		//定义map封装获取的数据;
		 HashMap map=new HashMap();
		 
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//发送get请求
		HttpGet get = new HttpGet("http://m.weather.com.cn/d/town/index?lat=39.9219&lon=116.44355");
		//模拟浏览器添加请求头
		get.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36");
		CloseableHttpResponse response = httpClient.execute(get);
		
		//获取请求网页的返回状态码 如:200
		int code = response.getStatusLine().getStatusCode();
		System.out.println("状态码:"+code);
		//将请求数据转为entity;
		HttpEntity entity = response.getEntity();
		//网页内容
		 String content = EntityUtils.toString(entity,"UTF-8");//转化为字符串并设置编码类型;
		 
		//运用Jsoup解析html内容得到document对象。
		 Document document = Jsoup.parse(content);
		//根据网页标签获取内容 如:title     .first 取第一个值
		Element element = document.getElementsByTag("title").first();
		map.put("标题:", element.text());
		System.out.println("title"+element.text());
		//jsoup的选择器。类似css 获取页面上的你需要的信息的所在标签。一级一级从上往下查找 如: .cityName h2        是class="cityName" 下一级h2标签下的文字信息;
		Elements select = document.select(".wrap");
		//遍历。
	    for(Element s: select){
	    	map.put("城市:", s.text());
	    }
		Elements elements = document.select(".n_wd");
	    for(Element o: elements){
	    	map.put("气温:", o.text());
	    }
	    System.out.println(map.toString());
	   sendMsg(map.toString(), "手机号"); 
	}
	public static boolean sendMsg(String msg, String phone) throws HttpException, IOException {
		String url = "http://utf8.api.smschinese.cn/";
		// Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888
		HttpClient client = new HttpClient();
		HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
		params.setConnectionTimeout(6000);
		params.setSoTimeout(20000);


		PostMethod method = new PostMethod(url);
		method.getParams().setHttpElementCharset("UTF-8");
		method.getParams().setContentCharset("UTF-8");
		method.getParams().setCredentialCharset("UTF-8");


		method.addParameter("Uid", "*****");//你申请的SMS的名字
		method.addParameter("Key", "*****");
		method.addParameter("smsMob", phone);
		method.addParameter("smsText", msg);


		client.executeMethod(method);
		String string = method.getResponseBodyAsString();
		System.err.println(string);


		return true;
	}
}

你可能感兴趣的:(java爬虫,java发送短信,java获取网页信息,java查看天气信息)