如何向RESFULL API发出https POST Web请求?

时间:2019-01-04 11:53:33

标签: api http https

我需要使用HTTPS URL进行Web请求。但是它总是返回(403)错误。 HTTPS URL还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    dataMap := map[string]interface{}{} // own map
    data, err := json.Marshal(dataMap)
    if err != nil {
        panic(err)
    }

    req, err := http.NewRequest("POST", "https://newsapi.org/v2/everything", bytes.NewBuffer(data)) // replace url
    if err != nil {
        panic(err)
    }
    req.Header.Set("Content-Type", "application/json")

    resp, err := (&http.Client{}).Do(req) // send request
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body) // read body
    if err != nil {
        panic(err)
    }

    var jsonResp map[string]interface{} // response map
    err = json.Unmarshal(body, &jsonResp)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Response: %s\nStatus: %s\n", jsonResp, resp.Status)
}

输出为:

  

响应:map [状态:错误代码:apiKey缺少消息:您的API密钥丢失。将此内容附加到带有apiKey参数的URL上,或使用x-api-key HTTPheader。]

     

状态:401未经授权

仍然存在错误,但这是由服务器引起的,因为没有API密钥。

相关问题