duanjiashai9140 2018-01-02 11:23 采纳率: 0%
浏览 158
已采纳

在JSON中设置标头获取请求

I'm getting JSON resonse from an external API with the following way:

func Request(url string, contentType string) []byte {
    resp, err := http.Get(url)
    resp.Header.Set("Content-Type", contentType)
    if err != nil {
        log.Fatal(err)
    }

    body, err := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }

    return body
}

url := fmt.Sprintf("https://example.com/api/category/%s", category)
contentType := "application/json"
body := Request(url, contentType)

res := &JSONRespStruct{}
err := json.Unmarshal([]byte(body), res)
if err != nil {
    log.Fatal(err)
}

The problem if I start to benchmark my site with go-wrk, the server crashes with the following error message:

2018/01/02 12:13:35 invalid character '<' looking for beginning of value

I think the code try to parse the JSON response as HTML. How I can force to get the response as a JSON?

  • 写回答

1条回答 默认 最新

  • dpqvwgr74759 2018-01-02 13:43
    关注

    You probably want to set the header on the request. Setting the header on the response has no impact.

    func Request(url string, contentType string) []byte {
        req, err := http.NewRequest("GET", url, nil)
        if err != nil {
            log.Fatal(err)
        }
        req.Header.Set("Content-Type", contentType)
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        return body
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog