从Android访问工作HTTPService时遇到问题
问题描述:
我有一个工作的.Net WCF HTTP服务。如果我将URL放入I.E,FireFox或Google Chrome浏览器中,我会找回正确的流。但是当我尝试在Android应用程序(在Eclipse中运行)中访问相同的服务时,我得到一个带有详细消息“权限被拒绝”的socketException。该服务在我的机器上运行在Visual Studio网络托管服务器上,客户端也在我的机器上的android模拟器中运行。从Android访问工作HTTPService时遇到问题
获取该异常的行是: InputStream in = new BufferedInputStream(urlConnection.getInputStream());
(我对同一方案,其中URL是www.android.com和我得到“无效的URL”先前的帖子)
也许人有一个线索,为什么浏览器有没有问题和Android客户端获得权限被拒绝? 感谢, 加里
HttpURLConnection urlConnection = null;
try
{
URL url = new URL("http://localhost:8080/TeamTask/Tasks");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
答
否认是最有可能不是在你的AndroidManifest.xml文件权限引起了许可。
此外,我还没有测试过它,但我会想象使用“localhost”将无法开始工作,因为它在仿真器上运行,就像使用本地主机的VM机器指向VM一样,而不是主机 - 放入你机器的IP地址。我目前正在测试来自不同机器的一些Android HTTP调用,并且只是输入我的服务器的本地IP。
编辑:
最后,这里是一些尝试和真正的代码,我定期使用制作简单HTTP调用:
public String getURLcontents(URL url) throws IOException{
String response = "failed";
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.v(TAG, "Opening connection: " + url.toString());
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
response = new Scanner(in).useDelimiter("\\A").next();
}
catch (Exception e) {
urlConnection.disconnect();
return response = "failed";
}
finally {
urlConnection.disconnect();
Log.v(TAG, "Closed connection");
}
return response;
}
TomJ,感谢您的回答。我现在可以读取流。 – 2012-04-05 16:51:31
有趣的(也不是很令人愉快的)副作用:如果你在* test *项目中使用HttpUrlConnection,你的* main *项目中必须有android.permission.INTERNET,即使主项目甚至不会执行HttpUrlConnection调用。 – 2013-10-10 20:47:28