大家好,有个问题问下大家,我在模拟器上跑一个读取网页的工程,代码如下:public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
//http地址
String httpUrl = "http://127.0.0.1:8080/http1.jsp";
//获得的数据
String resultData = "";
URL url = null;
try
{
//构造一个URL对象
url = new URL(httpUrl);
}
catch (MalformedURLException e)
{
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null)
{
try
{
//使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//得到读取的内容(流)
InputStream tmp = urlConn.getInputStream(); //这句代码执行回异常,为什么???
InputStreamReader in = new InputStreamReader(tmp);
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null))
{
//我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
//关闭InputStreamReader
in.close();
//关闭http连接
urlConn.disconnect();
//设置显示取得的内容
if ( resultData != null )
{
mTextView.setText(resultData);
}
else
{
mTextView.setText("读取的内容为NULL");
}
}
catch (IOException e)
{
Log.e(DEBUG_TAG, "异常");
}
}
else
{
Log.e(DEBUG_TAG, "Url NULL");
}
}结果发现,上面的getInputStream处执行不下去,会有异常,但是同样是这段代码,我新建一个Java工程,然后跑Java工程,发现是正常的。这是为什么? 我的模拟器是2.1的,能访问网络,在AndroidManifest.xml中也添加了INTERNET权限,但是我在模拟器上输入网址http://127.0.0.1:8080/http1.jsp访问不到,难道和这个有关系,还是有其他的原因呢?
{
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
//http地址
String httpUrl = "http://127.0.0.1:8080/http1.jsp";
//获得的数据
String resultData = "";
URL url = null;
try
{
//构造一个URL对象
url = new URL(httpUrl);
}
catch (MalformedURLException e)
{
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null)
{
try
{
//使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//得到读取的内容(流)
InputStream tmp = urlConn.getInputStream(); //这句代码执行回异常,为什么???
InputStreamReader in = new InputStreamReader(tmp);
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null))
{
//我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
//关闭InputStreamReader
in.close();
//关闭http连接
urlConn.disconnect();
//设置显示取得的内容
if ( resultData != null )
{
mTextView.setText(resultData);
}
else
{
mTextView.setText("读取的内容为NULL");
}
}
catch (IOException e)
{
Log.e(DEBUG_TAG, "异常");
}
}
else
{
Log.e(DEBUG_TAG, "Url NULL");
}
}结果发现,上面的getInputStream处执行不下去,会有异常,但是同样是这段代码,我新建一个Java工程,然后跑Java工程,发现是正常的。这是为什么? 我的模拟器是2.1的,能访问网络,在AndroidManifest.xml中也添加了INTERNET权限,但是我在模拟器上输入网址http://127.0.0.1:8080/http1.jsp访问不到,难道和这个有关系,还是有其他的原因呢?
应该加在Application的外层才对啊!