golang HTTP客户端

Get, Head, Post, and PostForm 可以构成 HTTP (or HTTPS) requests:


resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})

客户端必须关闭response的body:

resp, err := http.Get("http://example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...

 

TCP客户端设置超时的方法:

c := http.Client{
        Transport: &http.Transport{
            Dial: func(netw, addr string) (net.Conn, error) {
                deadline := time.Now().Add(25 * time.Second)
                c, err := net.DialTimeout(netw, addr, time.Second*20)
                if err != nil {
                    return nil, err
                }
                c.SetDeadline(deadline)
                return c, nil
            },
        },
    }

 

一些客户端请求的其他设定:

client := &http.Client{
    CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...

 要是想在NewRequest里面带上post数据,就必须传入一个io.Reader的body,这个body如果实现了io.Closer,那么返回的Request.body赋给这个body,然后通过Do或者Post什么的关闭。这个实现了io.Reader的body,基本上是通过构成?a=1&b=2这样的query的url.Values转化的,可以通过url.Values.add和set构建,前者可叠加,后者会覆盖之前的值,url.Values有一个Encode可以转化出相应的query字符串,然后再通过strings.NewReader()转换成io.Reader接口,就行了。还可以通过ioutil.NopCloser返回一个带Closer的io.reader

另外post数据的时候记得带上头:

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

 

下面这个还不知道什么意思

For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:

tr := &http.Transport{
    TLSClientConfig:    &tls.Config{RootCAs: pool},
    DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")

 

 

具体的一个例子:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "net"
    "time"
    "os"
    "strings"
)

// func nothing() {
//     fmt.Println("nothing")
//     client := &http.Client{}
//     a := strings.Contains("a", "b")
//     u:=&url.URL{}
//     r, err := u.Parse("baidu.com")
//     os.Exit(0)
// }

const (
    LHST = "http://127.0.0.1:3000/"
)

func main() {

    client := &http.Client{
        Transport: &http.Transport{
            Dial: func(netw, addr string) (net.Conn, error) {
                deadline := time.Now().Add(25 * time.Second)
                c, err := net.DialTimeout(netw, addr, time.Second*20)
                if err != nil {
                    return nil, err
                }
                c.SetDeadline(deadline)
                return c, nil
            },
        },
    }
 
    form := url.Values{}
    form.Set("username", "gao")
    b := strings.NewReader(form.Encode())
    req, err := http.NewRequest("POST", LHST+"answer", b)
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    res, err := client.Do(req)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
        os.Exit(0)
    }
    defer res.Body.Close()

    body,err:=ioutil.ReadAll(res.Body)
    fmt.Println(string(body))
}

再举个例子

func main() { host :
= "http://www.minigps.net/l.do?" client := http.Client{} q := url.Values{} q.Set("c", "454") q.Set("n", "6") q.Set("a", "8010") q.Set("e", "6652663") req, _ := http.NewRequest("GET", host+q.Encode(), nil) req.Header.Add("Content-Type","application/json;charset=UTF-8") res, err := client.Do(req) if err != nil { fmt.Println(err) os.Exit(-1) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) fmt.Println(string(body)) }

 

posted @ 2014-02-02 21:42  ggaaooppeenngg  阅读(1713)  评论(0编辑  收藏  举报