37

我正在尝试使用 Go 登录网站并存储 cookie 以供以后使用。

您能否提供发布表单、存储 cookie 以及使用 cookie 访问另一个页面的示例代码?

我想我可能需要通过研究http://gotour.golang.org/src/pkg/net/http/client.go来创建一个客户端来存储 cookie

package main

import ("net/http"
        "log"
        "net/url"
        )

func Login(user, password string) string {
        postUrl := "http://www.pge.com/eum/login"

        // Set up Login
        values := make(url.Values)
        values.Set("user", user)
        values.Set("password", password)

        // Submit form
        resp, err := http.PostForm(postUrl, values)
        if err != nil {
                log.Fatal(err)
        }
        defer resp.Body.Close()

        // How do I store cookies?
        return "Hello"
}

func ViewBill(url string, cookies) string {

//What do I put here?

}
4

5 回答 5

76

Go 1.1引入了一个 cookie jar 实现net/http/cookiejar

import (
    "net/http"
    "net/http/cookiejar"
)

jar, err := cookiejar.New(nil)
if err != nil { // error handling }

client := &http.Client{
    Jar: jar,
}
于 2013-10-15T16:44:16.380 回答
21

首先,您需要实现http.CookieJar接口。然后,您可以将其传递给您创建的客户端,它将用于客户端发出的请求。作为一个基本示例:

package main

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

type Jar struct {
    lk      sync.Mutex
    cookies map[string][]*http.Cookie
}

func NewJar() *Jar {
    jar := new(Jar)
    jar.cookies = make(map[string][]*http.Cookie)
    return jar
}

// SetCookies handles the receipt of the cookies in a reply for the
// given URL.  It may or may not choose to save the cookies, depending
// on the jar's policy and implementation.
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.lk.Lock()
    jar.cookies[u.Host] = cookies
    jar.lk.Unlock()
}

// Cookies returns the cookies to send in a request for the given URL.
// It is up to the implementation to honor the standard cookie use
// restrictions such as in RFC 6265.
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies[u.Host]
}

func main() {
    jar := NewJar()
    client := http.Client{nil, nil, jar}

    resp, _ := client.PostForm("http://www.somesite.com/login", url.Values{
        "email": {"myemail"},
        "password": {"mypass"},
    })
    resp.Body.Close()

    resp, _ = client.Get("http://www.somesite.com/protected")

    b, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()

    fmt.Println(string(b))
}
于 2012-10-06T05:20:02.440 回答
15

在 Go 的 1.5 版本中,我们可以使用 http.NewRequest 使用 cookie 发出 post 请求。

package main                                                                                              
import "fmt"
import "net/http"
import "io/ioutil"
import "strings"

func main() {
    // Declare http client
    client := &http.Client{}

    // Declare post data
    PostData := strings.NewReader("useId=5&age=12")

    // Declare HTTP Method and Url
    req, err := http.NewRequest("POST", "http://localhost/", PostData)

    // Set cookie
    req.Header.Set("Cookie", "name=xxxx; count=x")
    resp, err := client.Do(req)
    // Read response
    data, err := ioutil.ReadAll(resp.Body)

    // error handle
    if err != nil {
        fmt.Printf("error = %s \n", err);
    }   

    // Print response
    fmt.Printf("Response = %s", string(data));
}           
于 2016-03-10T17:45:40.727 回答
4

net/http/cookiejar是一个不错的选择,但我想知道在提出请求时实际需要哪些 cookie。您可以像这样获取响应 cookie:

package main
import "net/http"

func main() {
   res, err := http.Get("https://stackoverflow.com")
   if err != nil {
      panic(err)
   }
   for _, c := range res.Cookies() {
      println(c.Name, c.Value)
   }
}

你可以像这样添加cookie:

package main
import "net/http"

func main() {
   req, err := http.NewRequest("GET", "https://stackoverflow.com", nil)
   if err != nil {
      panic(err)
   }
   req.AddCookie(&http.Cookie{Name: "west", Value: "left"})
}
于 2021-04-07T17:45:04.817 回答
-3

另一种方法。适用于 Go 1.8。

    expiration := time.Now().Add(5 * time.Minute)
    cookie := http.Cookie{Name: "myCookie", Value: "Hello World", Expires: expiration}
    http.SetCookie(w, &cookie)
于 2017-05-25T14:58:44.723 回答