从Restful API获取POST类型方法的响应

How can I fetch the json response from the POST method? Currently I'm only able to fetch Status - 401 Unauthorized and StatusCode - 401

func postUrl(url string, byt []byte) (*http.Response, error) {
    tr := &http.Transport{
        DisableCompression: true,
    }
    client := &http.Client{Transport: tr, Timeout: 10 * time.Second}
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(byt))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")
    req.Header.Add("Authorization", "Basic "+basicAuth("username", "password"))
    resp, err := client.Do(req)
    return resp, err
  }

Above code produces the output:

{
  "errorMessages": [
    "You do not have the permission to see the specified issue.",
    "Login Required"
  ],
    "errors": {}
}
doutu2017
doutu2017 这个问题是凌乱的,完全无法理解。
3 年多之前 回复
dongleiqiao4906
dongleiqiao4906 切勿为每个请求创建新的传输。您将无法重用连接,并且任何空闲连接都将泄漏。从文档:传输应该被重用,而不是根据需要创建
3 年多之前 回复
drh37116
drh37116 嘿@user7354163-花点时间阅读有关如何撰写一个好的SO问题的文章:stackoverflow.com/help/how-to-ask
3 年多之前 回复

3个回答



无论您处于何种状态,读取响应的方式都是相同的。</ p>

 推迟res.Body.Close()
body,err:= ioutil.ReadAll(resp.Body)
</ code> </ pre>
</ div>

展开原文

原文

The way to read the response (if there is one) is the same regardless of what status you get.

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

As Frank said, regardless of the status code in the response you can simply read its body to use whatever content it has.

Particularly for the case of a JSON message, you have two options depending on whether you know the JSON message structure in advance (or want your code to depend on it).

If you know the structure and are ok with hard-coding it (plus you gain some type safety and better client code) you can have:

type ErrorResponse struct {
    Messages []string `json:"errorMessages"`
}

And then when you detect an error status code unmarshal the response body as that struct:

if resp.StatusCode % 100 != 2 {
    var error ErrorResponse
    err := json.Unmarshall(resp.Body, &error)
    // check err != nil ...
    // user error.ErrorMessages for whatever you want 
}

Alternatively if you don't want to depend on the JSON structure (to some degree) you can try to unmarshall it to a map[string]interface{} and try to use that in the generic way you think you can (generally not very useful).

This question is not related to http responses and http methods. Decode json string (wich is http response body in that case) with json decoder.

Simple example

(not directly related to your code snippet)

type Transition struct {
    Transition map[string]int
}

func main() {
    resp, err := postUrl(url, byt)
    if err != nil {
        log.Fatal(err)
    }

    var trans Transition
    decoder := json.NewDecoder(resp.Body)

    if err := decoder.Decode(&trans); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v
", trans)
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问