我正在尝试使用 http://ip-api.com/ api通过我的ip地址获取经度和纬度。当我访问 http://ip-api.com/json从我的浏览器或使用 curl,它以 json 格式返回正确的信息。但是,当我尝试从我的程序中使用 API 时,API 响应的主体是空的(或者看起来是这样)。
我正在尝试在此应用程序中执行此操作。 Ip_response_success 结构是根据此处的 api 文档制作的 http://ip-api.com/docs/api:json
type Ip_response_success struct {
as string
city string
country string
countryCode string
isp string
lat string
lon string
org string
query string
region string
regionName string
status string
timezone string
zip string
}
func Query(url string) (Ip_response_success, error) {
resp, err := http.Get(url)
if err != nil {
return Ip_response_success{}, err
}
fmt.Printf("%#v\n", resp)
var ip_response Ip_response_success
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&ip_response)
if err != nil {
return Ip_response_success{}, err
}
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%#v\n", string(body))
return ip_response, nil
}
func main() {
ip, err := Query("http://ip-api.com/json")
if err != nil {
fmt.Printf("%#v\n", err)
}
}
但最奇怪的是响应的正文是空白的。它在响应中给出了 200 状态代码,因此我假设 API 调用没有错误。 API 没有提到任何身份验证要求或用户代理要求,事实上,当我 curl 它或通过浏览器访问它时,它似乎不需要任何特殊的东西。我的程序中有什么地方做错了还是我使用的 API 有误?
我尝试在代码中打印响应,但 resp.body 只是显示为空白。打印 http.Response 结构的示例响应:
&http.Response{Status:"200 OK", StatusCode:200, Proto:"HTTP/1.1", ProtoMajor:1,
ProtoMinor:1, Header:http.Header{"Access-Control-Allow-Origin":[]string{"*"},
"Content-Type":[]string{"application/json; charset=utf-8"}, "Date":
[]string{"Tue, 21 Jun 2016 06:46:57 GMT"}, "Content-Length":[]string{"340"}},
Body:(*http.bodyEOFSignal)(0xc820010640), ContentLength:340, TransferEncoding:
[]string(nil), Close:false, Trailer:http.Header(nil), Request:(*http.Request)
(0xc8200c6000), TLS:(*tls.ConnectionState)(nil)}
如有任何帮助,我们将不胜感激!
最佳答案
首先,你必须读取正文,然后解析它:
body, err := ioutil.ReadAll(resp.Body)
err = json.NewDecoder(body).Decode(&ip_response)
if err != nil {
return Ip_response_success{}, err
}
另外,在 go 中,json 解码器必须能够访问结构的字段。这意味着它们必须暴露在您的包裹之外。
这意味着您使用 json 注释来指定映射:
type Ip_response_success struct {
As string `json: "as"`
City string `json: "city"`
Country string `json: "country"`
CountryCode string `json: "countryCode"`
Isp string `json: "isp"`
Lat float64 `json: "lat"`
Lon float64 `json: "lon"`
Org string `json: "org"`
Query string `json: "query"`
Region string `json: "region"`
RegionName string `json: "regionName"`
Status string `json: "status"`
Timezone string `json: "timezone"`
Zip string `json: "zip"`
}
另请注意,我根据服务器发送的数据,将Lon/Lat类型改为float64
关于api - 尝试查询 API,但 api 响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937407/
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h
我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path
我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"