Golang http.NewRequest: 无效的内容类型

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

Golang http.NewRequest: Invalid content-type

问题

我正在尝试使用Go的http.POST方法发布一个struct,但是我没有成功。

请看:

//SKUStock definition
type SkuStock struct {
    Sku      string `json:"id"`
    Quantity int64  `json:"stockQuantity"`
}

type StockJson struct {
    Items []SkuStock `json:"skus"`
}

从数据库加载一些数据后,为了执行POST请求本身,我有以下代码:

//Sends the skuStock Information to server
func SendSkuData(stockItems []SkuStock) {
    //creates a json like {"skus":[{"id":"ITEM1576","stockQuantity":995}]}
    stockPayload, err := json.Marshal(StockJson{stockItems})
    if err != nil {
        log.Fatal(err)
    }

    client := &http.Client{}

    apiRequestUrl := os.Getenv("api.protocol") + "://" + os.Getenv("api.address") + "/batch/sku/stock"
    req, err := http.NewRequest("POST", apiRequestUrl, bytes.NewBuffer(stockPayload))
    req.Header.Add("Content-Type", "application/json;charset=utf-8")
    req.SetBasicAuth(os.Getenv("api.key"), "")

    log.Printf("Request body: %s", string(stockPayload))
    log.Printf("Request %s", req)

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    log.Printf("Response %s", resp)
}

不幸的是,我从服务器收到的返回结果与预期不符:

2015/12/08 23:42:47 Request body: {"skus":[{"id":"ITEM1576","stockQuantity":995}]}
2015/12/08 23:42:47 Request &{POST http://api-sandbox.bonmarketplace.com.br/batch/sku/stock HTTP/1.1 1 1 map[Authorization:[Basic REMzRjAyNjUwNDE5RDAzQUJBNjEyM0E0QUZCMzJGQUQ6] Content-Type:[application/json;charset=utf-8]] {"skus":[{"id":"ITEM1576","stockQuantity":995}]} 48 [] false api-sandbox.bonmarketplace.com.br map[] map[] <nil> map[] <nil> <nil>}
2015/12/08 23:42:47 Response &{415 Unsupported Media Type 415 HTTP/1.1 1 1 map[Server:[nginx/1.7.5] Date:[Wed, 09 Dec 2015 01:40:18 GMT] Content-Type:[application/json;charset=utf-8] Content-Length:[163] Connection:[keep-alive] X-Access-Control-Realm:[external]] <nil> 163 [] false map[] <nil>}

编辑:插入了POST请求的主体(程序输出的第一行)。如果我在Postman中使用这个主体运行请求,它按预期工作。服务器不检查Accept头,只检查Content-Type头,而这个头已经设置为application/json;charset=utf-8

我做错了什么?我花了几个小时研究这个问题,但没有任何进展。

英文:

I am trying to post a struct using Go's http.POST, however I am not being succeeded with that.

Please look:

//SKUStock definition
type SkuStock struct {
    Sku string `json:&quot;id&quot;`;
	Quantity int64 `json:&quot;stockQuantity&quot;`;
}

type StockJson struct {
	Items []SkuStock `json:&quot;skus&quot;`;
}

After loading some data from a database, I have the following, in order to perform the POST itself:

//Sends the skuStock Information to server
func SendSkuData(stockItems []SkuStock) {

//creates a json like {&quot;skus&quot;:[{&quot;id&quot;:&quot;ITEM1576&quot;,&quot;stockQuantity&quot;:995}]}
	stockPayload, err := json.Marshal(StockJson{stockItems}); 
	if err != nil {
		log.Fatal(err);
	}

	client := &amp;http.Client{}

	apiRequestUrl := os.Getenv(&quot;api.protocol&quot;) + &quot;://&quot; + os.Getenv(&quot;api.address&quot;) + &quot;/batch/sku/stock&quot;;
	req, err := http.NewRequest(&quot;POST&quot;, apiRequestUrl, bytes.NewBuffer(stockPayload));
	req.Header.Add(&quot;Content-Type&quot;, &quot;application/json;charset=utf-8&quot;);
	req.SetBasicAuth(os.Getenv(&quot;api.key&quot;), &quot;&quot;);

    log.Printf(&quot;Request body: %s&quot;, string(stockPayload));
	log.Printf(&quot;Request %s&quot;, req);

	resp, err := client.Do(req);
	if(err != nil) {
		log.Fatal(err);
	}
	defer resp.Body.Close();

	log.Printf(&quot;Response %s&quot;, resp);

}

Unfortunately, the return I get from server is not as expected:

2015/12/08 23:42:47 Request body: {&quot;skus&quot;:[{&quot;id&quot;:&quot;ITEM1576&quot;,&quot;stockQuantity&quot;:995}]}
2015/12/08 23:42:47 Request &amp;{POST http://api-sandbox.bonmarketplace.com.br/batch/sku/stock HTTP/1.1 %!s(int=1) %!s(    int=1) map[Authorization:[Basic REMzRjAyNjUwNDE5RDAzQUJBNjEyM0E0QUZCMzJGQUQ6] Content-Type:[application/    json;charset=utf-8]] {{&quot;skus&quot;:[{&quot;id&quot;:&quot;ITEM1576&quot;,&quot;stockQuantity&quot;:995}]}} %!s(int64=48) [] %!s(bool=false) api-sandbox.    bonmarketplace.com.br map[] map[] %!s(*multipart.Form=&lt;nil&gt;) map[]   %!s(*tls.ConnectionState=&lt;nil&gt;) %!s(&lt;-chan struct     {}=&lt;nil&gt;)}
2015/12/08 23:42:47 Response &amp;{415 Unsupported Media Type %!s(int=415) HTTP/1.1 %!s(int=1) %!s(int=1) map[Server:[    nginx/1.7.5] Date:[Wed, 09 Dec 2015 01:40:18 GMT] Content-Type:[application/json;charset=utf-8] Content-Length:[163]     Connection:[keep-alive] X-Access-Control-Realm:[external]] %!s(*http.bodyEOFSignal=&amp;{0xc820122000 {0 0} false &lt;nil&gt;     0xd78a0 0xd7840}) %!s(int64=163) [] %!s(bool=false) map[] %!s(*http.Request=&amp;{POST 0xc820064480 HTTP/1.1 1 1 map[Content-    Type:[application/json;charset=utf-8] Authorization:[Basic REMzRjAyNjUwNDE5RDAzQUJBNjEyM0E0QUZCMzJGQUQ6]] {0xc82000e460}     48 [] false api-sandbox.bonmarketplace.com.br map[] map[] &lt;nil&gt; map[]   &lt;nil&gt; &lt;nil&gt;}) %!s(*tls.ConnectionState=&lt;nil&gt;)}

Edit: inserted the post body(first line on program's output). If I run the request on Postman, with this body, it works as expected. Server does not check Accept header, just the Content-Type, which is already set to application/json;charset=utf-8.

What am I doing wrong? I have spent the last hours looking into this, but no luck at all.

答案1

得分: 4

打印响应体后,返回了以下内容:

2015/12/09 00:32:11 响应体 {"httpStatusCode":415,"errorCode":"415","message":"Content-type:[application/json;charset=utf-8] invalido. Utilizar content-type:[application/json;charset=UTF-8]"}

从葡萄牙语翻译过来的: "无效的Content-Type。请使用application/json;charset=UTF-8

问题出在使用了UTF-8字符串的大小写,应该是大写,而不是之前的小写。感谢@evanmcdonnal和@CodingPickle的支持。

英文:

After printing the response body, the following has been returned:

2015/12/09 00:32:11 Response Body {&quot;httpStatusCode&quot;:415,&quot;errorCode&quot;:&quot;415&quot;,&quot;message&quot;:&quot;Content-type:[application/json;charset=utf-8] invalido. Utilizar content-type:[application/json;charset=UTF-8]&quot;}

From portuguese: "Invalid Content-Type. Please use application/json;charset=UTF-8.

The detail was in the case used on UTF-8 string, which should be uppercase, not lower as previously. Thanks @evanmcdonnal and @CodingPickle for support.

huangapple
  • 本文由 发表于 2015年12月9日 09:11:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/34169073.html
匿名

发表评论

匿名网友

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

确定