我知道这个问题已经被问过很多次了,但是我找不到合适的答案来解决我的问题,希望你们中的一个能帮助我;-)
我正在尝试使用智能手机设备上的 Android 应用程序与休息网络服务进行通信(因此没有模拟器)。
Web 服务在 Windows 机器上的 192.168.0.2:8080
上运行。
该设备连接在与 pc 相同的 wlan 网络中。
当我使用设备的 chrome 浏览器打开链接时,web 服务响应正常。
这是我用来在 AsyncTask 中连接到网络服务的代码:
protected Integer doInBackground(String... params)
{
try
{
AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
HttpPost post = new HttpPost(params[0]);
String xml = new ScoreDto(new Random(System.currentTimeMillis()).nextLong()).toXml();
post.setEntity(new StringEntity(xml));
return client.execute(post).getStatusLine().getStatusCode();
}
catch (Exception e)
{
Log.e(TAG, e.getLocalizedMessage());
return 0;
}
}
- 我尝试连接时使用了几种不同的方法,但总是导致连接超时
- 我在我的应用程序中加入了互联网许可。
- 我暂时关闭了 windows pc 上的本地防火墙。
- 我尝试了设备的端口转发
- 我尝试从应用
httpbin.org/ip
中调用不同的网络服务并获得有效响应。
有什么想法吗?问题似乎与本地网络有关.. 如果我想通过我的 Android 设备连接到外部服务器,是否需要特殊限制或权限? 提前致谢;-)
最佳答案
感谢所有发表评论试图提供帮助的人。
我弄清楚出了什么问题:
发布请求缺少 content-type
header ...
一个功能齐全的 doBackground
- 实现如下所示:
protected Integer doInBackground(String... params)
{
try
{
//TODO check if params.length >=2 & not empty
AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
HttpPost post = new HttpPost(params[0]);
post.setHeader("content-type", "application/xml");
post.setEntity(new StringEntity(params[1]));
return client.execute(post).getStatusLine().getStatusCode();
}
catch (Exception e)
{
Log.e(TAG, e.getLocalizedMessage());
return 0;
}
}
关于java - 将 Android App 连接到 restful webservice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28076120/