繁体   English   中英

如何正确从 GO 中的 url 获取内容?

[英]How proper get content from url in GO?

例如,我需要来自页面https://aliexpress.ru/item/4001275226820.html的内容

在邮递员和浏览器中,我得到页面的 html 内容

但是当我尝试使用 GO 时,我无法获取内容

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("https://aliexpress.ru/item/4001275226820.html")
    defer resp.Body.Close()

    if err != nil {panic(err)}

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

    fmt.Printf("%s\n", html)
}

但是让恐慌“在 10 次重定向后停止”我做错了什么?

下面的代码给我一个 200 响应。 您也许可以简化它,但应该足以让您入门:

package main

import (
   "fmt"
   "net/http"
)

func cookies() ([]*http.Cookie, error) {
   req, err := http.NewRequest(
      "HEAD", "https://login.aliexpress.ru/sync_cookie_write.htm", nil,
   )
   if err != nil {
      return nil, err
   }
   val := req.URL.Query()
   val.Set("acs_random_token", "1")
   req.URL.RawQuery = val.Encode()
   res, err := new(http.Transport).RoundTrip(req)
   if err != nil {
      return nil, err
   }
   return res.Cookies(), nil
}

func main() {
   req, err := http.NewRequest(
      "HEAD", "https://aliexpress.ru/item/4001275226820.html", nil,
   )
   if err != nil {
      panic(err)
   }
   cooks, err := cookies()
   if err != nil {
      panic(err)
   }
   for _, cook := range cooks {
      if cook.Name == "xman_f" {
         req.AddCookie(cook)
      }
   }
   res, err := new(http.Transport).RoundTrip(req)
   if err != nil {
      panic(err)
   }
   fmt.Printf("%+v\n", res)
}

暂无
暂无

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

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