如何在运行在Android上的Go程序中访问互联网?

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

How to get access to the Internet from a Go program running on Android?

问题

我的程序在安卓终端中无法访问互联网,但在Linux中可以正常工作。
(在安卓终端中,wget(busybox)可以正常访问互联网)

package main

import (
	"io"
	"io/ioutil"
	"net/http"
)

func Url(url string) (string, io.ReadCloser, http.Header, error) {
	var c = http.Client{}
	inf, err := c.Get(url)
	if err == nil {
		data, _ := ioutil.ReadAll(inf.Body)
		return string(data), inf.Body, inf.Header, err
	}
	return "", nil, nil, err
}

func main() {
	print("test internet... ")
	c, _, _, err := Url("http://ifconfig.me/ip")
	if err == nil {
		println("\n ip:", c)
	} else {
		println("error")
	}
}

编译命令:

go build main.go    # Linux
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build $(bin).go    # 安卓
英文:

My program can't access to internet when put in android terminal, but in linux works fine.
(wget (busybox) works fine with internet in android terminal)

package main

import (
	"io"
	"io/ioutil"
	"net/http"
)

func Url(url string)(string, io.ReadCloser, http.Header, error){
	var c = http.Client{}
	inf, err := c.Get(url)
	if err == nil {
		data,_ := ioutil.ReadAll(inf.Body)
		return string(data), inf.Body, inf.Header, err
	}
	return "", nil, nil, err
}

func main() {
	print("test internet...	")
	c,_,_,err := Url("http://ifconfig.me/ip")
	if err == nil {
		println("\n ip:", c)
	}else{
		println("error")
	}
}

compiling with:

go build main.go    # linux
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build $(bin).go    # android

答案1

得分: 2

Android没有/etc/resolv.conf文件。

在你的代码中的某个地方,或者更可能是你导入的其中一个库中,你假设了传统的Linux用户空间,而在Android上并非如此。

也许"GOOS=linux"是错误的根源。

英文:

Android does not have an /etc/resolv.conf

Somewhere in your code, or more likely one of those libraries you import, you are assuming a traditional linux userspace, which is not the case on Android.

maybe the "GOOS=linux" is the source of the mistake.

答案2

得分: 1

Android目前还没有完全支持Go语言。如果将来Android添加了Go的软件开发工具包(SDK),这将变得更容易。但是目前,除非你愿意修改Go的源代码或编写自己的一套库来处理Android不同的环境,否则这将变得困难甚至不可能。

英文:

Android does not have full support for Go yet. If at some point in the future they add a Go sdk this will be easier. But for right now unless you feel like modifying Go's source yourself or writing your own set of libraries to handle Androids different environment this is going to be difficult to impossible.

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

发表评论

匿名网友

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

确定