doudu2404
2014-10-11 14:25
浏览 143
已采纳

错误:EOF用于读取Post请求的XML正文

I'm getting error: EOF on console when I read the XML response body.

Below is my code.

resp, err := http.Post(url, "application/xml", payload)
if err != nil {
    response.WriteErrorString(http.StatusInternalServerError, err.Error())
    return
}

defer resp.Body.Close()
dec := xml.NewDecoder(resp.Body)

if debug == true {
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println("=========== Response ==================")
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Println(string(body))
    fmt.Println("=========== Response Ends =============")
}

err = dec.Decode(respStruct)

I suspect ioutil.ReadAll is not working as expected.

Is there a reason why it's throwing this error?

图片转代码服务由CSDN问答提供 功能建议

当我读取XML响应正文时,在控制台上出现 error:EOF

下面是我的代码。

  resp,err:= http.Post(URL,“ application / xml”,有效载荷)\  nif err!= nil {
 response.WriteErrorString(http.StatusInternalServerError,err.Error())
 return 
} 
 
defer.Body.Close()
dec:= xml.NewDecoder(resp.Body  )
 
if debug == true {
 body,err:= ioutil.ReadAll(resp.Body)
 fmt.Println(“ ===========响应======  ============)
,如果出错!=无{
 fmt.Printf(“错误:%v”,err)
返回
} 
 fmt.Println(string  (body))
 fmt.Println(“ ============响应结束=============)
} 
 
err = dec.Decode  (respStruct)
   
 
 

我怀疑 ioutil.ReadAll 无法正常工作。

是 为何会引发此错误?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dttphb59319 2014-10-11 14:31
    已采纳

    xml.NewDecoder(resp.Body) might already have read the content of resp.Body.
    Hence the EOF message.

    You can see the same error in "xml.NewDecoder(resp.Body).Decode Giving EOF Error"

    Reading the resp.Body first, and using the string with xml.Unmarshal would avoid the double read and the error message.

    Note: a similar answer shows that the best practice remains to use xml.Decoder instead of xml.Unmarshal when reading from streams.
    So make sure you don't read resp.Body twice, and it will work.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题