问题描述
我使用 HttpURLConnection类
的连接方法,但它返回空
。
没有其他的消息没有printstack只是空。
I am using HttpURLConnection
's connect method but it returns null
.no other message no printstack just null.
URL url = new URL("http://whatever");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
在上面也返回空
不知道为什么会这样来了。但我无法连接到网络。
Don't know why this comes. But I cant connect to net.
我也试图与HttpURLConnection类和URLConnection都是不同的例子。
i also tried with HttpURLConnection and urlconnection both are different example.
推荐答案
您说您正在使用 HttpURLConnection类
但在code你波斯特的URLConnection
。这是你如何作出正确的 HttpURLConnection类
:
You said you are using HttpURLConnection
but in the code you poste URLConnection
. This is how you make a proper HttpURLConnection
:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
您还必须做在主线程超出这个连接(使用的AsyncTask
或其他方式)或其他应用程序将崩溃。
You also have to do this connection outside the main thread (Using AsyncTask
or other method) or otherwise the app will crash.
另外添加正确的权限是:
Also add the right permissions for it:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
希望它帮助!祝你好运!
Hope it helps! Good Luck!
这篇关于不能在我的Android应用程序连接到互联网只。每种方法连接互联网返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!