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

Wesley13
• 阅读 449

最近两天想实现一个登陆网站就可以自动显示该地区的的天气情况。很是苦恼。慢慢研究然后才其所得。
研究的思路大致是这样的。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定位以及天气预报的功能
你会发现每个城市都有一个编号,你可以百度复制到然后通过io字符串处理例如这样
java 用sevlet实现ip定位以及天气预报的功能
通过百度接口获取的名称,在通过io按照行读取遍历找到这个城市的编号,返回
3:通过返回的号拼接地址,抓取,谷歌浏览器先抓包分析要抓去的层次内容:
java 用sevlet实现ip定位以及天气预报的功能
下面先附上没涉及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;              
        }
    }
}

祝君好运,一起加油。

本文分享 CSDN - Big sai。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
2年前
unity将 -u4E00 这种 编码 转汉字 方法
 unity中直接使用 JsonMapper.ToJson(对象),取到的字符串,里面汉字可能是\\u4E00类似这种其实也不用转,服务器会通过类似fastjson发序列化的方式,将json转对象,获取对象的值就是中文但是有时服务器要求将传参中字符串中类似\\u4E00这种转汉字,就需要下面 publ
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这