繁体   English   中英

前往:XML API返回奇数编码的字符串

[英]Go: XML API returns oddly encoded string

我正在尝试从API解析XML响应,当调用fmt.Println并传递响应主体时,我得到了一个奇怪的字符串:

&{0xc8200e6140 {0 0} false <nil> 0xc2030 0xc1fd0}

我已经确认可以按预期curl API并获取XML。 (我也收到与Postman Chrome扩展程序发送GET请求相同的响应。)这是编码问题吗?

以下是相关代码:

type Album struct {
    Title     string `xml:"album>name"`
    Artist    string `xml:"album>artist>name"`
    PlayCount uint64 `xml:"album>playcount"`
}

const lastFMAPIKey string = "<My api key>"
const APIURL string = "http://ws.audioscrobbler.com/2.0/"

func perror(err error) {
    if err != nil {
        panic(err)
    }
}

func getListeningInfo(url string) []byte {
    resp, err := http.Get(url)
    perror(err)
    defer resp.Body.Close()
    // this is the line that prints the string above
    fmt.Println(resp.Body)
    body, err2 := ioutil.ReadAll(resp.Body)
    perror(err2)
    return body
}

func main() {
    url := APIURL + "?method=user.getTopAlbums&user=iamnicholascox&period=1month&limit=1&api_key=" + lastFMAPIKey
    album := Album{}
    err := xml.Unmarshal(getListeningInfo(url), &album)
    perror(err)
    fmt.Printf(album.Artist)
}

作为参考,打印出resp而不是仅resp.Body给出以下内容:

{200 OK 200 HTTP/1.1 1 1 map[Ntcoent-Length:[871]
Connection:[keep-alive] Access-Control-Max-Age:[86400]
Cache-Control:[private] Date:[Thu, 03 Dec 2015 05:16:34 GMT]
Content-Type:[text/xml; charset=UTF-8]
Access-Control-Request-Headers:[Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date,
Content-Type, X-Atmosphere-Transport, *]
Access-Control-Allow-Methods:[POST, GET, OPTIONS]
Access-Control-Allow-Origin:[*]
Server:[openresty/1.7.7.2]]
0xc8200f6040 -1 [] false map[] 0xc8200b8000 <nil>}

http.Response的主体是io.ReaderCloser。 您看到的奇数输出是用作响应主体的struct字段的值。

如果要打印出实际内容,则必须先从正文中阅读。

试试ioutil。 ReadAll通过执行以下操作:

b, err := ioutil.ReadAll(resp.Body) // b is a []byte here
if err != nil { 
   fmt.Println("Got error:",err)
} else {
    fmt.Println(string(b)) // convert []byte to string for printing to the screen.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM