【问题标题】:How to make a https POST Web Request to RESFULL API?如何向 RESTFUL API 发出 https POST Web 请求?
【发布时间】:2019-01-04 11:53:32
【问题描述】:

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

【问题讨论】:

    标签: api http https


    【解决方案1】:

    你可以试试这个:

    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[状态:错误代码:apiKeyMissing 消息:您的 API 密钥丢失。使用 apiKey 参数将此附加到 URL,或使用 x-api-key HTTPheader。]

    状态:401 未授权

    还是有错误,不过是服务器造成的,因为没有API key。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2015-01-26
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2016-05-12
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多