我试图用Go编写Web客户端,但是当我检查http请求的正文的返回值时,我得到了一个数字数组,而不是文本。

这是产生输出的程序的最隔离版本。我想我无法使用ioutil做某事,但不知道是什么。

package main

import "fmt"
import "net/http"
import "io/ioutil"

func main() {
    resp, err := http.Get("http://test.com/")
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Print(body)
}

输出结果如下:

[239 187 191 60 33 68 79 67 84 89 80 69 32 104 116 109 108 ...

而不是test.com返回的测试

最佳答案

ioutil.ReadAll() 返回一个 byte slice ([]byte),而不是string(加上error)。

将其转换为string,就可以了:

fmt.Print(string(body))

参见以下简单示例(在Go Playground上尝试):
var b []byte = []byte("Hello")

fmt.Println(b)
fmt.Println(string(b))

输出:
[72 101 108 108 111]
Hello

关于http - 从http调用转到带有ioutil : returning array of (ASCII?)数字的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28343085/

10-11 22:36
查看更多