java获取本机公网ip接口

package com.ini.ip;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author KYOXUE
 */
@WebServlet(name="ip",description="获取本机官网IP",urlPatterns = { "/get"},loadOnStartup=1)
public class IpService  extends HttpServlet{
    private static final long serialVersionUID = 1L;
    private final static String QUERY_IP_ROOT="http://www.ip138.com/";
    private final static String CONTENT_ENCODING="GB2312";
    String getContent(String action,String content_encoding)throws Exception{
        URLConnection conn = null; 
        InputStream is = null;
        String ret = "";
        try {
            URL url = new URL(action);
            conn = url.openConnection();
            is = conn.getInputStream();
            int len;
            byte buf[] = new byte[40];
            while((len=is.read(buf))!=-1){
                   ret += new String(buf,content_encoding);
            }
        } catch (Exception e) {
            throw e;
        }finally{
            if (is!=null) {
                try {
                    is.close();
                } catch (Exception e2) {
                }
            }
        }
        return ret;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = "";
        PrintWriter print = null;
        try {
            print = resp.getWriter();
            resp.setContentType("text/html;charset=utf-8");
            String rootHtml = getContent(QUERY_IP_ROOT, CONTENT_ENCODING);
            String startIndex = "<iframe src=\"";
            String endIndex = "\" rel=\"nofollow\" frameborder=\"0\" scrolling=\"no\"></iframe>";
            int start =  rootHtml.indexOf(startIndex);
            int end =  rootHtml.indexOf(endIndex);
            String ipRequest = rootHtml.substring(start+startIndex.length(),end);
            if (null == ipRequest || ipRequest.length() == 0) {
                result="404";
                return;
            }
            String ip = getContent(ipRequest, CONTENT_ENCODING);
            String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";  
            Pattern p = Pattern.compile(regex);  
            Matcher m = p.matcher(ip); 
            if(m.find()){
                result=m.group(0);
            }else{
                result="404";
                return;
            }
        } catch (Exception e) {
            result="500";
        }finally{
            try {
                if (print!=null) {
                    print.print(result);
                    print.flush();
                    print.close();
                }
            } catch (Exception e2) {
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ip</display-name>
    <welcome-file-list>
        <welcome-file>/ip</welcome-file>
    </welcome-file-list>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

servlet工程,可以右键工程,搜web,选择dynamic web project

posted @ 2018-06-13 18:09  稚语希听  阅读(619)  评论(0)    收藏  举报