去HTTP Post并使用Cookies [英] Go HTTP Post and use Cookies
本文介绍了去HTTP Post并使用Cookies的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您可以举出发布表单的示例代码,将表单存储为cookies,并使用cookie访问另一个页面?
我想我可能需要让客户端存储cookie,方法是学习 http://gotour.golang.org/src/pkg/net/http/client.go
包主
导入(net / http
log
net / url
)
func登录(用户名,密码字符串)string {
postUrl:=http://www.pge.com/eum/login
//设置登录
值:= make(url.Values)
values.Set(user,user)
values.Set(密码),密码)
//提交表格
resp,err:= http.PostForm(postUrl,values)
if err!= nil {
log。致命(错误)
}
推迟resp.Body.Close()
//如何存储cookie?
returnHello
}
func ViewBill(url string,cookies)string {
//我在这里放什么?
$ b $ / code>
解决方案
一个href =http://golang.org/doc/go1.1> 1.1 引入了一个cookie jar实现 net / http / cookiejar
。
import (
net / http
net / http / cookiejar
)
cookieJar,_:= cookiejar.New(nil)
client:=& http.Client {
Jar:cookieJar,
}
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?
}
解决方案
Go 1.1 introduced a cookie jar implementation net/http/cookiejar
.
import (
"net/http"
"net/http/cookiejar"
)
cookieJar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: cookieJar,
}
这篇关于去HTTP Post并使用Cookies的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文