最近两天想实现一个登陆网站就可以自动显示该地区的的天气情况。很是苦恼。慢慢研究然后才其所得。
研究的思路大致是这样的。ip 定位–>通过位置获取天气。首先声明一下,以前国家气象局的接口已经被封,以前直接传一个json数据就有天气情况,现在需要手动解析下。
所以,这样的实际思路为:ip获取地址(操作获取城市名称)------百度下载各城市对应编号---------io字符串处理(你方便得到的)------通过城市名获取编号---------通过编号组成网页url访问---------截取你所需要的部分。
1:首先,你要做的事可以通过ip访问到你的地理位置,百度地图api免费并且挺好用的。百度api
​​​http://api.map.baidu.com/location/ip​​ //HTTP协议

​https://api.map.baidu.com/location/ip​​ //HTTPS

协议你要先申请下才能获取ak,你要访问的地址 其实是http://api.map.baidu.com/location/ip?ak=“你的ak”;如果有ip加上:&ip="";他返回的是一个json串,你可以用阿里的fastjson解析他,获取你想要的东西。

2:有了地址之后,在上中国气象局官网

java 用sevlet实现ip定位以及天气预报的功能_sevlet


你会发现每个城市都有一个编号,你可以百度复制到然后通过io字符串处理例如这样

java 用sevlet实现ip定位以及天气预报的功能_sevlet_02


通过百度接口获取的名称,在通过io按照行读取遍历找到这个城市的编号,返回

3:通过返回的号拼接地址,抓取,谷歌浏览器先抓包分析要抓去的层次内容:

java 用sevlet实现ip定位以及天气预报的功能_json_03


下面先附上没涉及web端的测试代码:爬取分析工具:jsuop fastjson

获取地址 调用方法主类

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class 地址 {
public static void main(String[] args) throws IOException
{
Document doc=Jsoup.connect("http://api.map.baidu.com/location/ip?ak=nZFzpfoHLDVD3pEPGaSrGCYebppWx7ge").ignoreContentType(true).get();
// System.out.println(doc.text());
JSONObject jsonObj = JSON.parseObject(doc.text());
// System.out.println(jsonObj);
JSONObject jsonObj1=jsonObj.getJSONObject("content").getJSONObject("address_detail");
String jsonObj2=(String) jsonObj1.get("city");
System.out.println(jsonObj2);//这就是城市名
/*
* 获取城市对应编号
*/
city city=new city();
String number= city.getcity(jsonObj2);
System.out.println(number);
/*
* 获取天气信息
*/
String weather=new search().weather(number);
System.out.println(jsonObj2 ":" weather);

}
}

返回城市编号

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class city {
public city(){}
public String getcity(String city) throws IOException{
{

String citynumber="";
File file=new File("E:/bianhao2.txt");
FileReader in=new FileReader(file);
BufferedReader buf=new BufferedReader(in);
String s="";
while((s=buf.readLine())!=null)
{
String a[]=s.split(":");
//System.out.println(a[0]);
if(a[0].equals(city.substring(0, city.length()-1)))
{

citynumber=a[1];
}

}
in.close();
buf.close();
//System.out.println(citynumber);
return citynumber;
}

}
}

返回天气信息,简单爬虫不做过多解释

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class search {
public search() {}
public String weather(String bianhao) throws IOException
{
String url="http://www.weather.com.cn/weather/" bianhao ".shtml";
Document doc=Jsoup.connect(url).get();
Elements links=doc.getElementsByClass("sky skyid lv3 on");
//System.out.println(links.text());
return links.text();
}
}

上述是测试主机。如果整合到web上,有几点注意的
1:request方法获取客户端ip正常事可以的,但是获取本机会是ipv6。并且这个ip也查不到地理位置,所以就需要判断是否为本机,如果市本机就默认使用不带ip(不带ip是解析本机)。
2:通过session传递数据。跳转到该网页但url不变。
3:输入流,这就是很坑的地方,如果正常的字符流在windows上是没问题的,但是部署到linnux服务器上会乱码,并且linux的sevlet不好调试还得从新导入。试了很多方法才发现原来是我的字符编码没设置好(设置成utf不行你可以试试)。注意流的关闭
4:sesson.jsp网页自行设计,传递的内容只需session.getAttribute(“tf”),即可获取。注意访问页面第一次要访问sevlet。我也不知道为什么。
sevlet代码为

import java.io.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class weather extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");//防止乱码
response.setCharacterEncoding("UTF-8");
String path=this.getServletContext().getRealPath("/");
String ip=request.getRemoteAddr();
String localip=request.getLocalAddr();
//System.out.print(ip " " localip " " ip.equals(localip));
String url="http://api.map.baidu.com/location/ip?ak=nZFzpfoHLDVD3pEPGaSrGCYebppWx7ge";
if(!ip.equals(localip)){url ="&ip=" ip;}
Document doc=Jsoup.connect(url).ignoreContentType(true).get();
// System.out.println(doc.text());
JSONObject jsonObj = JSON.parseObject(doc.text());
// System.out.println(jsonObj);
JSONObject jsonObj1=jsonObj.getJSONObject("content").getJSONObject("address_detail");
String jsonObj2=(String) jsonObj1.get("city");//获取城市名称
// System.out.println(jsonObj2);
String number= getcity(request, jsonObj2, path);
// System.out.println(number);
String weather=jsonObj2 ":" getweather(number);
// System.out.println(weather);

request.getSession().setAttribute("tf",weather);
RequestDispatcher dis= request.getRequestDispatcher("session.jsp");//传输数据
dis.forward(request,response);//
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

this.doGet(request, response);
}
//解析中国天气网

public String getweather(String bianhao) throws IOException
{
String url="http://www.weather.com.cn/weather/" bianhao ".shtml";
Document doc=Jsoup.connect(url).get();
Elements links=doc.getElementsByClass("sky skyid lv3 on");
//System.out.println(links.text());
return links.text();
}

//返回城市代码号
public String getcity(HttpServletRequest request,String city,String path) throws IOException{
{

String citynumber="";
File file=new File(path "image/bianhao2.txt");//System.out.print(file.getAbsolutePath());
citynumber=file.getAbsolutePath();

//FileReader in=new FileReader(file);
InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"GB2312");
BufferedReader buf=new BufferedReader(isr);
String s="";
while((s=buf.readLine())!=null)
{
String a[]=s.split(":");

//System.out.println(a[0]);
if(a[0].equals(city.substring(0, city.length()-1)))
{
citynumber=a[1];
return citynumber;
}
}
isr.close();
buf.close();
//System.out.println(citynumber);
return citynumber;
}
}
}

祝君好运,一起加油。