英文:
Equivalent function for url.openStream() in Golang
问题
以下是用Go语言实现读取和打印HTML源代码的示例代码:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("http://www.oracle.com/")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}
你可以使用上述代码来读取并打印HTML源代码。首先,我们使用http.Get
函数获取URL的响应。然后,我们使用ioutil.ReadAll
函数读取响应的内容,并将其转换为字符串进行打印。
希望对你有帮助!如果你有任何其他问题,请随时问我。
英文:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
I need to do the same in golang
i.e read and print the html source code, but cannot find the relation between two, I am a beginner with Go language, thank you in advance
答案1
得分: 3
希望这可以帮到你:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func Error(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
response, err := http.Get("http://www.oracle.com/")
Error(err)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
Error(err)
fmt.Printf("%s\n", contents)
}
更多详情请参考:https://golang.org/pkg/net/http/
英文:
Hope this will help:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func Error(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
response, err := http.Get("http://www.oracle.com/")
Error(err)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
Error(err)
fmt.Printf("%s\n", contents)
}
For more details: https://golang.org/pkg/net/http/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论