在GO语言中进行HTTP POST请求时出现错误。

huangapple go评论87阅读模式
英文:

HTTP POST in GO Lang throws error

问题

我正在尝试使用GO语言进行POST请求。API URL期望在请求体中传递一个用户名和密码字段。然而,我一直收到以下错误信息:

我不确定我在这里做错了什么?

错误信息:

 url.Values未定义(类型string没有Values字段或方法)

GO函数:

func makeHttpPostReq(url string, username string, password string){

    client := http.Client{}
	req, err := http.NewRequest("POST", url, url.Values{"username": {username}, "password": {password}})
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	if err != nil {
		 fmt.Println("无法连接到服务器。")
	} else {
		 body, _ := ioutil.ReadAll(resp.Body)
		 fmt.Println("body=", string(body))
	}

}
英文:

I am trying to make a Post request using in GO Lang. The API URL is expecting a username and password field to be passed to it in body. However I keep getting the below error ?

I am not sure what am i doing wrong here ?

Error

 url.Values undefined (type string has no field or method Values)

Go Function

func makeHttpPostReq(url string, username string, password string){

    client := http.Client{}
	req, err := http.NewRequest("POST", url, url.Values{"username": {username}, "password": {password}})
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	if err != nil {
		 fmt.Println("Unable to reach the server.")
	} else {
		 body, _ := ioutil.ReadAll(resp.Body)
		 fmt.Println("body=", string(body))
	}

}

答案1

得分: 4

makeHttpPostReq的参数表明url是一个字符串,但你将其作为结构体url.Values来处理,因此出现了错误

没有字段或方法

英文:

The argument to makeHttpPostReq states url is a string but you are treating it as a struct url.Values, thus the error

> has no field or method

答案2

得分: 2

你正在重复使用url这个词。

在你的情况下,url被解析为一个字符串,而不是net/url

英文:

You are reusing the url word.

url is in your case resolving to url as a string not a net/url

huangapple
  • 本文由 发表于 2015年6月15日 08:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/30835847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定