Golang Go语言中 请问如何获取 post 请求返回体的字符类型为[]uint8但格式是xml的转换成json
null
Golang Go语言中 请问如何获取 post 请求返回体的字符类型为[]uint8但格式是xml的转换成json
body, err := ioutil.ReadAll(res.Body)
fmt.Println(“post send success”)
fmt.Printf(“type is %T\n”, body)
结果:
post send success
type is []uint8
<?xml version=“1.0” encoding=“utf-8” ?><returnsms>
<errorstatus>
<error>2</error>
<remark>sign 参数错误</remark>
</errorstatus>
</returnsms>
更多关于Golang Go语言中 请问如何获取 post 请求返回体的字符类型为[]uint8但格式是xml的转换成json的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
<?xml version=“1.0” encoding=“utf-8” ?><returnsms>
<errorstatus>
<error>2</error>
<remark>sign 参数错误</remark>
</errorstatus>
</returnsms>
是 string() 后的打印结果
直接打印 body 是
body is []byte{0x3c, 0x3f, 0x78, 0x6d, 0x6c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x31, 0x2e, 0x30, 0x22, 0x20, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x3d, 0x22, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x22, 0x20, 0x3f, 0x
3e, 0x3c, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x73, 0x6d, 0x73, 0x3e, 0xa, 0x20, 0x3c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x3e, 0xa, 0x20, 0x3c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x3e, 0x32, 0x3c, 0x2f, 0x65, 0x72, 0x7
2, 0x6f, 0x72, 0x3e, 0xa, 0x20, 0x3c, 0x72, 0x65, 0x6d, 0x61, 0x72, 0x6b, 0x3e, 0x73, 0x69, 0x67, 0x6e, 0xe5, 0x8f, 0x82, 0xe6, 0x95, 0xb0, 0xe9, 0x94, 0x99, 0xe8, 0xaf, 0xaf, 0x3c, 0x2f, 0x72, 0x65, 0x6d, 0x61, 0x72, 0x6b, 0x3e, 0xa, 0x20, 0x3c
, 0x2f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x3e, 0xa, 0x20, 0x3c, 0x2f, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x73, 0x6d, 0x73, 0x3e, 0xa, 0x20}
有没有大佬给个思路呀
这个其实网上一搜 一大堆。
鸟哥那图谁来贴一下?
在 Go 语言中,处理 POST 请求返回的 XML 数据并将其转换为 JSON 格式涉及几个步骤。你可以使用标准库中的 net/http
包来发送请求和接收响应,然后使用 encoding/xml
和 encoding/json
包来解析和转换数据。以下是一个示例代码片段:
- 定义一个结构体来映射 XML 数据。
- 使用
encoding/xml
解析响应体为结构体实例。 - 将结构体实例转换为 JSON。
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
type XMLData struct {
XMLName xml.Name `xml:"root"`
Field1 string `xml:"field1"`
Field2 int `xml:"field2"`
}
func main() {
resp, err := http.Post("http://example.com/api", "application/xml", nil)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var xmlData XMLData
if err := xml.Unmarshal(body, &xmlData); err != nil {
panic(err)
}
jsonData, err := json.Marshal(xmlData)
if err != nil {
panic(err)
}
fmt.Println(string(jsonData))
}
注意:
- 替换
XMLData
结构体中的字段以匹配你的 XML 结构。 - 确保请求的 URL 和请求体(在示例中为
nil
,需根据你的需求设置)。 ioutil.ReadAll
会读取整个响应体到内存中,对于大响应体,考虑流式处理。