這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
主要示範go語言自動登入HTPPS串連及cookie的使用,如何解析JSON資料等特性
https返回的json資料格式為
type item struct { Id, List_type, Severity int list_type_string, Name, Expiration string list_type_name, Severity_name string}type resData struct { Total_count, Total_page, Expect_page, Num_per_page int Sort_by, Sort_order string List []item}
注意結構體必須是大寫字母開頭的成員才會被json.Unmarshal()處理到,對應的資料範例:
{ "total_count" : 366, "total_page" : 1, "expect_page" : 1, "num_per_page" : 10000000, "sort_by" : "id", "sort_order" : "desc", "list" : [{ "id" : 3263, "list_type" : 2, "list_type_string" : "File", "name" : "4CDA46B428405E8A155A3AA32E4F25C8EA09B707", "severity" : 3, "expiration" : "11\/14\/2014 04:51:06", "list_type_name" : "File", "severity_name" : "High" }, { "id" : 3262, "list_type" : 2, "list_type_string" : "File", "name" : "ECC3F6D2CB227981C12038D620336617C8EC0B64", "severity" : 3, "expiration" : "11\/12\/2014 10:02:21", "list_type_name" : "File", "severity_name" : "High" } ] }
go源碼如下
// https project main.gopackage mainimport ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/cookiejar" "net/url")type item struct { Id, List_type, Severity int list_type_string, Name, Expiration string list_type_name, Severity_name string}type resData struct { Total_count, Total_page, Expect_page, Num_per_page int Sort_by, Sort_order string List []item}func check(err error) { if err != nil { panic(err) }}func main() { //登入URL,即提供帳號登入的URL loginUrl := "https://10.64.71.8/cgi-bin/logon.cgi" loginData := url.Values{"usrname": {"admin"}, "passwd": {"trend#11"}, "isCookieEnable": {"1"}} //目標URL,即需要訪問的URL targetUrl := "https://10.64.71.8/php/blacklist_whitelist_query.php" targetData := url.Values{"action": {"query"}, "black_or_white": {"sandbox"}, "expect_page": {"1"}, "num_per_page": {"10000000"}, "list_type": {"99"}, "keyword": {""}, "sort_by": {"id"}, "sort_order": {"desc"}} var resp *http.Response var err error var data []byte tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, DisableCompression: true, } client := &http.Client{Transport: tr} //啟用cookie client.Jar, _ = cookiejar.New(nil) resp, err = client.PostForm(loginUrl, loginData) check(err) resp, err = client.PostForm(targetUrl, targetData) check(err) if data, err = ioutil.ReadAll(resp.Body); err == nil { fmt.Printf("%s\n", data) }//解析返回的JSON資料 var message resData err = json.Unmarshal(data, &message) check(err) fmt.Printf("%+v\n", message) fmt.Printf("%v\t%v\n", message.Total_count, message.List[0].Name)}