doupin8555 2016-10-02 10:11
浏览 109
已采纳

Golang HTTP XML解析问题

I'm trying to access an XML file available online, but after the GET the XML format disappears.
What am I doing wrong?
Thank you so much!

func getHttp(address string) string{
    resp, err := http.Get(address)
    resp.Header.Add("Content-Type","application/xml; charset=utf-8")
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    return (string(data))
}

The new format looks like this:

{"SessionKey":"229eaeaa9fb14a0d85ff38ae4e0c7870_ecilpojl_018FC93424D13ECC0908CE5BC5E3F86B","Query":{"Country":"GB","Currency":"GBP","Locale":"en-gb","Adults":1,"Children":0,"Infants":0,"OutboundDate":"2016-10-08","LocationSchema":"Default","CabinClass":"Economy","GroupPricing":false},

instead of

<SessionKey>229eaeaa9fb14a0d85ff38ae4e0c7870_ecilpojl_018FC93424D13ECC0908CE5BC5E3F86B</SessionKey>
  <Query>
    <Country>GB</Country>
    <Currency>GBP</Currency>
    <Locale>en-gb</Locale>
    <Adults>1</Adults>
    <Children>0</Children>
    <Infants>0</Infants>
    <OutboundDate>2016-10-08</OutboundDate>
    <LocationSchema>Default</LocationSchema>
    <CabinClass>Economy</CabinClass>
    <GroupPricing>false</GroupPricing>
  </Query>
  • 写回答

1条回答 默认 最新

  • dongpi9494 2016-10-02 11:15
    关注

    See: https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending

    Try this (and replace the web address with yours):

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    func main() {
        fmt.Println(getHttp(`http://stackoverflow.com/`))
    }
    func getHttp(url string) string {    
        client := &http.Client{}
        req, err := http.NewRequest("GET", url, nil)
        if err != nil {
            panic(err)
        }
        req.Header.Set("ACCEPT", "application/xhtml+xml,application/xml")
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
        data, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            panic(err)
        }
        return string(data)
    }
    

    I hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料