Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26312053
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2009-11-16 11:13:58

整理代码能够直接运行的示例:
1、抓取IP138上面的IP地理位置
/**
     * @see 实现编码乱码问题
     * */
    public String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"gbk"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           try {
            is.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
      }
      return sb.toString();
     }

/**
     * @author Administrator
     * @return ip对应的城市名称
     * */
    public void getCityByIp() {
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost("" , 80, "http");       
        PostMethod post = new PostMethod( "/ips.asp" );
        NameValuePair simcard = new NameValuePair( "ip" , this.ipString);
        post.setRequestBody( new NameValuePair[] { simcard});       
        try {
            client.executeMethod(post);
            InputStream iStream = post.getResponseBodyAsStream();
            String contentString = convertStreamToString(iStream);
            Pattern p = Pattern.compile("来自.*
");//正则匹配出来
            Matcher m = p.matcher(contentString);
            while(m.find()) {
               String content = m.group();
               System.out.println("Match:" + content.replaceAll("]+>",""));
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

能够实现输入IP地址返回此IP所在的地理位置出来!


阅读(1019) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~