使用`http.NewRequest(...)`做一个URL编码的POST请求 [英] Make a URL-encoded POST request using `http.NewRequest(...)`

查看:2557
本文介绍了使用`http.NewRequest(...)`做一个URL编码的POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要发送一个POST请求到一个发送我的数据的API为 application / x-www-form-urlencoded 内容类型。由于我需要管理请求标头,因此我使用 http.NewRequest (method,urlStr string,body io.Reader) 方法创建一个请求。对于这个POST请求,我将我的数据查询添加到URL中,并将主体留空,如下所示:

  package main 

导入(
字节
fmt
净/ http
净/网址
strconv


func main(){
apiUrl:=https://api.com
resource:=/ user /
data:= url.Values {}
data.Set(name,foo)
data.Add(surname,bar)

u,_:= url .ParseRequestURI(apiUrl)
u.Path = resource
u.RawQuery = data.Encode()
urlStr:= fmt.Sprintf(%v,u)//https: //api.com/user/?name=foo&surname=bar

client:=& http.Client {}
r,_:= http.NewRequest(POST ,urlStr,nil)
r.Header.Add(Authorization,auth_token = \XXXXXXX \)
r.Header.Add(Content-Type,application / (data.Encode())))

resp,x-www-form-urlencoded)
r.Header.Add(Content-Length,strconv.Itoa _:= client.Do(r)
fmt.Println(resp.Status)
}

当我回应时,我总是得到 400 BAD REQUEST 。我相信这个问题依赖于我的请求,API不知道我发布了哪个有效载荷。我知道诸如 Request.ParseForm ,但不确定如何在这种情况下使用它。也许我错过了一些头,也许有更好的方式发送有效载荷作为 application / json 类型使用身体参数?

解决方案

必须在 body http.NewRequest(method,urlStr string,body io.Reader)方法的参数,作为实现 io.Reader interface。



基于示例代码:

 包主要

导入(
fmt
净/ http
净/网址
strconv
字符串


func main(){
apiUrl:=https://api.com
resource:=/ user /
data:= url.Values {}
data.Set(name,foo)
data.Add(surname,bar)

u,_:= url.ParseRequestURI(apiUrl)
u.Path =资源
urlStr:= u.String()//'https://api.com/user/'

client:=& http.Cl客户端{}
r,_:= http.NewRequest(POST,urlStr,strings.NewReader(data.Encode()))// URL编码的有效载荷
r.Header.Add(Authorization ,auth_token = \XXXXXXX \)
r.Header.Add(Content-Type,application / x-www-form-urlencoded)
r.Header。添加(Content-Length,strconv.Itoa(len(data.Encode())))

resp,_:= client.Do(r)
fmt.Println(resp .Status)
}

resp.Status 200 OK 这种方式。


I want to make a POST request to an API sending my data as a application/x-www-form-urlencoded content type. Due to the fact that I need to manage the request headers, I'm using the http.NewRequest(method, urlStr string, body io.Reader) method to create a request. For this POST request I append my data query to the URL and leave the body empty, something like this:

package main

import (
    "bytes"
    "fmt"
    "net/http"
    "net/url"
    "strconv"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Add("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    u.RawQuery = data.Encode()
    urlStr := fmt.Sprintf("%v", u) // "https://api.com/user/?name=foo&surname=bar"

    client := &http.Client{}
    r, _ := http.NewRequest("POST", urlStr, nil)
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

As I response, I get always a 400 BAD REQUEST. I believe the problem relies on my request and the API does not understand which payload I am posting. I'm aware of methods like Request.ParseForm, not really sure how to use it in this context though. Maybe am I missing some further Header, maybe is there a better way to send payload as a application/json type using the body parameter?

解决方案

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Add("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // 'https://api.com/user/'

    client := &http.Client{}
    r, _ := http.NewRequest("POST", urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

这篇关于使用`http.NewRequest(...)`做一个URL编码的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆