drqyxkzbs21968684 2010-01-24 14:44
浏览 47
已采纳

将代码从PHP转换为Ruby on Rails

I'm trying to use geoip's web service for a ruby on rails application. They don't give any ruby demos but this is what they give for PHP. I was wondering if anyone knew how to convert this to work on ruby on rails? I only need the city and the region from the data. More examples can be found at their site at

$query = "http://geoip3.maxmind.com/b?l=" . $license_key . "&i=" . $ipaddress;
$url = parse_url($query);
$host = $url["host"];
$path = $url["path"] . "?" . $url["query"];
$timeout = 1;
$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
or die('Can not open connection to server.');
if ($fp) {
  fputs ($fp, "GET $path HTTP/1.0
Host: " . $host . "

");
  while (!feof($fp)) {
    $buf .= fgets($fp, 128);
  }
  $lines = split("
", $buf);
  $data = $lines[count($lines)-1];
  fclose($fp);
} else {
  # enter error handing code here
}

echo $data;
$geo = explode(",",$data);
$country = $geo[0];
$state = $geo[1];
$city = $geo[2];
$lat = $geo[3];
$lon = $geo[4];

展开全部

  • 写回答

1条回答 默认 最新

  • dsgd4654674 2010-01-24 14:53
    关注

    I don't have a geoip license key so cannot test it fully, but this should work:

    require 'net/http'
    
    url = 'http://geoip3.maxmind.com/b?l=%s&i=%s' % [license_key, ip_address]
    res = Net::HTTP.get_response(URI.parse(url))
    
    lines = res.body.split("
    ")
    
    geo = lines[-1].split(',')
    
    country = geo[0]
    state = geo[1]
    city = geo[2]
    lat = geo[3]
    lon = geo[4]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥50 关于#php#的问题,请各位专家解答!
  • ¥15 python 3.8.0版本,安装官方库ibm_db遇到问题,提示找不到ibm_db模块。如何解决?
  • ¥15 TMUXHS4412如何防止静电,
  • ¥30 Metashape软件中如何将建模后的图像中的植被与庄稼点云删除
  • ¥20 机械振动学课后习题求解答
  • ¥15 IEC61850 客户端和服务端的通讯机制
  • ¥15 MAX98357a(关键词-播放音频)
  • ¥15 Linux误删文件,请求帮助
  • ¥15 IBMP550小型机使用串口登录操作系统
  • ¥15 关于#python#的问题:现已知七自由度机器人的DH参数,利用DH参数求解机器人的逆运动学解目前使用的PSO算法
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部