Go HTTP Post并使用Cookies

huangapple go评论120阅读模式
英文:

Go HTTP Post and use Cookies

问题

package main

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

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

  1. // Set up Login
  2. values := make(url.Values)
  3. values.Set("user", user)
  4. values.Set("password", password)
  5. // Submit form
  6. resp, err := http.PostForm(postUrl, values)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. defer resp.Body.Close()
  11. // Store cookies
  12. cookies := resp.Cookies()
  13. return cookies

}

func ViewBill(url string, cookies []*http.Cookie) string {
client := &http.Client{}

  1. // Create a new request
  2. req, err := http.NewRequest("GET", url, nil)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. // Add cookies to the request
  7. for _, cookie := range cookies {
  8. req.AddCookie(cookie)
  9. }
  10. // Send the request
  11. resp, err := client.Do(req)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. defer resp.Body.Close()
  16. // Read the response body
  17. body, err := ioutil.ReadAll(resp.Body)
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. return string(body)

}

英文:

I'm trying to use Go to log into a website and store the cookies for later use.

Could you give example code for posting a form, storing the cookies, and accessing another page using the cookies?

I think I might need to make a Client to store the cookies, by studying http://gotour.golang.org/src/pkg/net/http/client.go

  1. package main
  2. import ("net/http"
  3. "log"
  4. "net/url"
  5. )
  6. func Login(user, password string) string {
  7. postUrl := "http://www.pge.com/eum/login"
  8. // Set up Login
  9. values := make(url.Values)
  10. values.Set("user", user)
  11. values.Set("password", password)
  12. // Submit form
  13. resp, err := http.PostForm(postUrl, values)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. defer resp.Body.Close()
  18. // How do I store cookies?
  19. return "Hello"
  20. }
  21. func ViewBill(url string, cookies) string {
  22. //What do I put here?
  23. }

答案1

得分: 87

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

  1. import (
  2. "net/http"
  3. "net/http/cookiejar"
  4. )
  5. jar, err := cookiejar.New(nil)
  6. if err != nil {
  7. // 错误处理
  8. }
  9. client := &http.Client{
  10. Jar: jar,
  11. }
英文:

Go 1.1 introduced a cookie jar implementation net/http/cookiejar.

  1. import (
  2. "net/http"
  3. "net/http/cookiejar"
  4. )
  5. jar, err := cookiejar.New(nil)
  6. if err != nil {
  7. // error handling
  8. }
  9. client := &http.Client{
  10. Jar: jar,
  11. }

答案2

得分: 23

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "io/ioutil"
  7. "sync"
  8. )
  9. type Jar struct {
  10. lk sync.Mutex
  11. cookies map[string][]*http.Cookie
  12. }
  13. func NewJar() *Jar {
  14. jar := new(Jar)
  15. jar.cookies = make(map[string][]*http.Cookie)
  16. return jar
  17. }
  18. // SetCookies处理给定URL的回复中的cookie接收。
  19. // 根据jar的策略和实现,它可能会选择保存cookie,也可能不保存。
  20. func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
  21. jar.lk.Lock()
  22. jar.cookies[u.Host] = cookies
  23. jar.lk.Unlock()
  24. }
  25. // Cookies返回要在给定URL的请求中发送的cookie。
  26. // 是否遵守RFC 6265中的标准cookie使用限制取决于实现。
  27. func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
  28. return jar.cookies[u.Host]
  29. }
  30. func main() {
  31. jar := NewJar()
  32. client := http.Client{nil, nil, jar}
  33. resp, _ := client.PostForm("http://www.somesite.com/login", url.Values{
  34. "email": {"myemail"},
  35. "password": {"mypass"},
  36. })
  37. resp.Body.Close()
  38. resp, _ = client.Get("http://www.somesite.com/protected")
  39. b, _ := ioutil.ReadAll(resp.Body)
  40. resp.Body.Close()
  41. fmt.Println(string(b))
  42. }
英文:

First you'll need to implement the http.CookieJar interface. You can then pass this into the client you create and it will be used for requests made with the client. As a basic example:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "io/ioutil"
  7. "sync"
  8. )
  9. type Jar struct {
  10. lk sync.Mutex
  11. cookies map[string][]*http.Cookie
  12. }
  13. func NewJar() *Jar {
  14. jar := new(Jar)
  15. jar.cookies = make(map[string][]*http.Cookie)
  16. return jar
  17. }
  18. // SetCookies handles the receipt of the cookies in a reply for the
  19. // given URL. It may or may not choose to save the cookies, depending
  20. // on the jar's policy and implementation.
  21. func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
  22. jar.lk.Lock()
  23. jar.cookies[u.Host] = cookies
  24. jar.lk.Unlock()
  25. }
  26. // Cookies returns the cookies to send in a request for the given URL.
  27. // It is up to the implementation to honor the standard cookie use
  28. // restrictions such as in RFC 6265.
  29. func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
  30. return jar.cookies[u.Host]
  31. }
  32. func main() {
  33. jar := NewJar()
  34. client := http.Client{nil, nil, jar}
  35. resp, _ := client.PostForm("http://www.somesite.com/login", url.Values{
  36. "email": {"myemail"},
  37. "password": {"mypass"},
  38. })
  39. resp.Body.Close()
  40. resp, _ = client.Get("http://www.somesite.com/protected")
  41. b, _ := ioutil.ReadAll(resp.Body)
  42. resp.Body.Close()
  43. fmt.Println(string(b))
  44. }

答案3

得分: 17

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

  1. package main
  2. import "fmt"
  3. import "net/http"
  4. import "io/ioutil"
  5. import "strings"
  6. func main() {
  7. // 声明http客户端
  8. client := &http.Client{}
  9. // 声明post数据
  10. PostData := strings.NewReader("useId=5&age=12")
  11. // 声明HTTP方法和URL
  12. req, err := http.NewRequest("POST", "http://localhost/", PostData)
  13. // 设置cookie
  14. req.Header.Set("Cookie", "name=xxxx; count=x")
  15. resp, err := client.Do(req)
  16. // 读取响应
  17. data, err := ioutil.ReadAll(resp.Body)
  18. // 错误处理
  19. if err != nil {
  20. fmt.Printf("error = %s \n", err);
  21. }
  22. // 打印响应
  23. fmt.Printf("Response = %s", string(data));
  24. }
英文:

At the version 1.5 of Go, we can use http.NewRequest to make a post request with cookie.

  1. package main
  2. import "fmt"
  3. import "net/http"
  4. import "io/ioutil"
  5. import "strings"
  6. func main() {
  7. // Declare http client
  8. client := &http.Client{}
  9. // Declare post data
  10. PostData := strings.NewReader("useId=5&age=12")
  11. // Declare HTTP Method and Url
  12. req, err := http.NewRequest("POST", "http://localhost/", PostData)
  13. // Set cookie
  14. req.Header.Set("Cookie", "name=xxxx; count=x")
  15. resp, err := client.Do(req)
  16. // Read response
  17. data, err := ioutil.ReadAll(resp.Body)
  18. // error handle
  19. if err != nil {
  20. fmt.Printf("error = %s \n", err);
  21. }
  22. // Print response
  23. fmt.Printf("Response = %s", string(data));
  24. }

答案4

得分: 6

net/http/cookiejar是一个不错的选择,但是我喜欢知道在发送请求时实际上需要哪些cookie。你可以像这样获取响应的cookie:

  1. package main
  2. import "net/http"
  3. func main() {
  4. res, err := http.Get("https://stackoverflow.com")
  5. if err != nil {
  6. panic(err)
  7. }
  8. for _, c := range res.Cookies() {
  9. println(c.Name, c.Value)
  10. }
  11. }

你可以像这样添加cookie:

  1. package main
  2. import "net/http"
  3. func main() {
  4. req, err := http.NewRequest("GET", "https://stackoverflow.com", nil)
  5. if err != nil {
  6. panic(err)
  7. }
  8. req.AddCookie(&http.Cookie{Name: "west", Value: "left"})
  9. }
英文:

net/http/cookiejar is a good option, but I like to know what cookies are
actually required when making my requests. You can get the response cookies
like this:

  1. package main
  2. import "net/http"
  3. func main() {
  4. res, err := http.Get("https://stackoverflow.com")
  5. if err != nil {
  6. panic(err)
  7. }
  8. for _, c := range res.Cookies() {
  9. println(c.Name, c.Value)
  10. }
  11. }

and you can add cookies like this:

  1. package main
  2. import "net/http"
  3. func main() {
  4. req, err := http.NewRequest("GET", "https://stackoverflow.com", nil)
  5. if err != nil {
  6. panic(err)
  7. }
  8. req.AddCookie(&http.Cookie{Name: "west", Value: "left"})
  9. }

答案5

得分: -3

另一种方法是这样做。在Go 1.8中有效。

  1. expiration := time.Now().Add(5 * time.Minute)
  2. cookie := http.Cookie{Name: "myCookie", Value: "Hello World", Expires: expiration}
  3. http.SetCookie(w, &cookie)
英文:

Another way of doing it. Works in Go 1.8.

  1. expiration := time.Now().Add(5 * time.Minute)
  2. cookie := http.Cookie{Name: "myCookie", Value: "Hello World", Expires: expiration}
  3. http.SetCookie(w, &cookie)

huangapple
  • 本文由 发表于 2012年10月6日 12:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/12756782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定