使用 HTTP Post 并使用 Cookie [英] Go HTTP Post and use Cookies

查看:98
本文介绍了使用 HTTP Post 并使用 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我想我可能需要通过研究 http://gotour.golang.org/src/pkg/net/http/client.go

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 引入了一个cookie jar 实现 net/http/cookiejar.>

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

这篇关于使用 HTTP Post 并使用 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆