Equivalent function for url.openStream() in Golang

huangapple go评论81阅读模式
英文:

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/

huangapple
  • 本文由 发表于 2015年10月24日 13:18:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/33314790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定