Go HTTP Post并使用Cookies

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

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"

// 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()

// Store cookies
cookies := resp.Cookies()

return cookies

}

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

// Create a new request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
	log.Fatal(err)
}

// Add cookies to the request
for _, cookie := range cookies {
	req.AddCookie(cookie)
}

// Send the request
resp, err := client.Do(req)
if err != nil {
	log.Fatal(err)
}
defer resp.Body.Close()

// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	log.Fatal(err)
}

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

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?

}

答案1

得分: 87

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

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

jar, err := cookiejar.New(nil)
if err != nil { 
  // 错误处理 
}

client := &http.Client{
	Jar: jar,
}
英文:

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

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

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

client := &http.Client{
	Jar: jar,
}

答案2

得分: 23

首先,您需要实现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处理给定URL的回复中的cookie接收。
// 根据jar的策略和实现,它可能会选择保存cookie,也可能不保存。
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.lk.Lock()
    jar.cookies[u.Host] = cookies
    jar.lk.Unlock()
}

// Cookies返回要在给定URL的请求中发送的cookie。
// 是否遵守RFC 6265中的标准cookie使用限制取决于实现。
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))
}
英文:

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:

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))
}

答案3

得分: 17

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

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

func main() {
    // 声明http客户端
    client := &http.Client{}

    // 声明post数据
    PostData := strings.NewReader("useId=5&age=12")

    // 声明HTTP方法和URL
    req, err := http.NewRequest("POST", "http://localhost/", PostData)

    // 设置cookie
    req.Header.Set("Cookie", "name=xxxx; count=x")
    resp, err := client.Do(req)
    // 读取响应
    data, err := ioutil.ReadAll(resp.Body)

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

    // 打印响应
    fmt.Printf("Response = %s", string(data));
}
英文:

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

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));
}           

答案4

得分: 6

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"})
}
英文:

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:

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)
   }
}

and you can add cookies like this:

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"})
}

答案5

得分: -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)
英文:

Another way of doing it. Works in Go 1.8.

	expiration := time.Now().Add(5 * time.Minute)
	cookie := http.Cookie{Name: "myCookie", Value: "Hello World", Expires: expiration}
	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:

确定