GO語言"net/http"包中"Get"函數的用法及代碼示例。
用法:
func Get(url string)(resp *Response, err error)
Get 向指定的 URL 發出 GET。如果響應是以下重定向代碼之一,則 Get 跟隨重定向,最多 10 個重定向:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect)
如果重定向過多或存在 HTTP 協議錯誤,則會返回錯誤。非 2xx 響應不會導致錯誤。任何返回的錯誤都是 *url.Error 類型。如果請求超時,url.Error 值的 Timeout 方法將報告 true。
當 err 為 nil 時,resp 總是包含一個非 nil 的 resp.Body。調用者在完成讀取後應關閉 resp.Body。
Get 是DefaultClient Get 的包裝。
要使用自定義標頭發出請求,請使用 NewRequest 和 DefaultClient 做。
要使用指定的 context.Context 發出請求,請使用 NewRequestWithContext 和 DefaultClient 做。
例子:
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode > 299 {
log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", body)
}
相關用法
- GO Getenv用法及代碼示例
- GO GoStringer用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
- GO NewFromFiles用法及代碼示例
- GO Regexp.FindString用法及代碼示例
- GO Time.Sub用法及代碼示例
- GO Regexp.FindAllIndex用法及代碼示例
- GO Encode用法及代碼示例
- GO ResponseRecorder用法及代碼示例
- GO Value用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Fscanln用法及代碼示例
- GO Values.Get用法及代碼示例
- GO NumError用法及代碼示例
- GO TrailingZeros8用法及代碼示例
- GO Logger.Output用法及代碼示例
- GO Float.SetString用法及代碼示例
- GO NewReader用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Get。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。