duan02468 2018-12-12 03:47
浏览 354
已采纳

如何在POST方法中传递标头?

Here I have a function in which I'm sending a POST request which is used to save customer in the squareup with data and also set the headers with Authentication using variable_name.Header.Set() But in body response it will always give me error of the:-

"errors":[
     {"category":"AUTHENTICATION_ERROR",
      "code":"UNAUTHORIZED",
      "detail":"Your request did not include an `Authorization` http header with an access token. }]}

But In the function I'm setting the authentication token.

Code:-

func CreateCustomer(c *gin.Context) {
customer := models.Customer{}
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")// token pass in the postman.
bearerToken := strings.TrimSpace(bearer[1])

customerErr := json.NewDecoder(c.Request.Body).Decode(&customer)
if customerErr != nil {
    fmt.Println(customerErr)
    return
}
fmt.Println(customer)
bindData, err := json.Marshal(customer)
if err != nil {
    panic(err)
}
var jsonStr = []byte(string(bindData))
url :="https://connect.squareup.com/v2/customers"
fmt.Println(url)

req, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
// I used this one too.
// req.Header.Set("Authorization", "Bearer "+bearerToken)
// req.Header.Set("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+bearerToken)
req.Header.Add("Accept", "application/json")
fmt.Println(req.Header)
if err != nil {
    panic(err)
}
defer req.Body.Close()
body, _ := ioutil.ReadAll(req.Body)
fmt.Println("response Body:", string(body))
}

type Customer struct {
  GivenName    string   `json:"given_name" bson:"given_name"`
  FamilyName   string   `json:"family_name" bson:"family_name"`
  CompanyName  string   `json:"company_name" bson:"company_name"`
  Nickname     string   `json:"nickname" bson:"nickname"`
  EmailAddress string   `json:"email_address" bson:"email_address"`
  Address      Addresss `json:"address" bson:"address"`
  PhoneNumber  string   `json:"phone_number" bson:"phone_number"`
  ReferenceId  string   `json:"reference_id" bson:"reference_id"`
  Note         string   `json:"note" bson:"note"`
}

The req.Header result is:-

map[X-Xss-Protection:[1; mode=block] 
    Keep-Alive:[timeout=60] 
    Accept:[application/json] 
    X-Permitted-Cross-Domain-Policies:[none] 
    Content-Type:[application/json] 
    Vary:[Origin, Accept-Encoding] 
    X-Content-Type-Options:[nosniff] 
    X-Download-Options:[noopen] 
    X-Frame-Options:[SAMEORIGIN] 
    Date:[Wed, 12 Dec 2018 03:41:16 GMT] 
    Strict-Transport-Security:[max-age=631152000] 
    Authorization:[Bearer YOUR_TOKEN HERE]]

Can anyone tell me that what error should I'm doing or where I do correction that it will able to save customer in the Squareup?

  • 写回答

1条回答 默认 最新

  • dtry54612 2018-12-12 04:00
    关注

    Your code sends POST request and after request is processed it adds headers to response struct:

    response, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))

    You should set headers first and send request after that:

    // create request
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    if err != nil {
       panic(err)
    }
    
    // set headers
    req.Header.Add("Authorization", "Bearer "+bearerToken)
    req.Header.Add("Accept", "application/json")
    
    // send request with headers
    client := &http.Client{}
    response, err := client.Do(req)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红