Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自golang的经过身份验证的http客户端请求_Http_Go - Fatal编程技术网

来自golang的经过身份验证的http客户端请求

来自golang的经过身份验证的http客户端请求,http,go,Http,Go,我有以下代码: client:=&http.client{} /*鉴定*/ req,err:=http.NewRequest(“GET”http://164.99.113.32/Authenticate“,无) 请求设置为(“,”) resp,err:=client.Do(请求) 如果出错!=零{ fmt.Printf(“错误:%s”,错误) } /*获取详细信息*/ req.URL,=URL.Parse(“http://164.99.113.32/Details") resp,err=clie

我有以下代码:

client:=&http.client{}
/*鉴定*/
req,err:=http.NewRequest(“GET”http://164.99.113.32/Authenticate“,无)
请求设置为(“,”)
resp,err:=client.Do(请求)
如果出错!=零{
fmt.Printf(“错误:%s”,错误)
}
/*获取详细信息*/
req.URL,=URL.Parse(“http://164.99.113.32/Details")
resp,err=client.Do(请求)
如果出错!=零{
fmt.Printf(“错误:%s”,错误)
}

现在,第二个http调用失败,出现401访问被拒绝错误。另一个REST客户端(firefox插件)正确地从服务器获取详细信息,因此我知道服务器端没有任何问题。我是否需要传递某种会话字符串或我们在上一个请求中获得的内容?

使用HTTP基本身份验证,每个请求都需要凭据。试着复制

req.SetBasicAuth("<username>", "<password>")
req.SetBasicAuth(“,”)
第二个client.Do(req)前面的行

Firefox插件获取详细信息的原因是浏览器将缓存HTTP Basic
用于后续使用的身份验证令牌。

好的。我已经解决了这个问题。我只需要创建一个饼干罐

我感到惊讶的是,golang http在默认情况下没有处理这个问题 请求/客户端类

我必须使用的代码是:

type myjar struct {
    jar map[string] []*http.Cookie
}

func (p* myjar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("The cookie being set is : %s\n", cookies)
    p.jar [u.Host] = cookies
}

func (p *myjar) Cookies(u *url.URL) []*http.Cookie {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("Cookie being returned is : %s\n", p.jar[u.Host])
    return p.jar[u.Host]
}
然后主要是:

    jar := &myjar{}
    jar.jar = make(map[string] []*http.Cookie)
    client.Jar = jar

工作。

有一个新的官方图书馆,也许这会有帮助

例如:

该方法是否验证密码是否正确?在我的例子中,当我传递错误的密码时,它会无声地失败。我可以回答我自己的问题。这可以通过
resp,err=client.Do(req)
延迟resp.Body.close()
如果resp.StatusCode!=200{log.Fatal(“HTTP响应代码不是200”)}
。因此,使用这种方法可以跟踪响应。