繁体   English   中英

将Android App连接到宁静的Web服务

[英]Connect Android App to restful webservice

我知道这个问题已经问了很多次了,但是我找不到正确的答案,希望你们中的一个能帮助我;-)

我正在尝试通过智能手机设备上的android应用程序与其他Web服务进行通信(因此没有模拟器)。 该Web服务在Windows计算机上的192.168.0.2:8080上运行。 设备与PC连接在相同的局域网中。 在使用设备的Chrome浏览器打开链接时,Web服务会正常响应。

这是我用来在AsyncTask中连接到Web服务的代码:

    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调用其他Web服务,并获得有效的响应。

有任何想法吗? 问题似乎已连接到本地网络。如果我想通过我的android设备连接到外部服务器,是否需要特殊的限制或权限? 提前致谢 ;-)

感谢所有发表评论以寻求帮助的人。
我发现了什么地方出了问题:
发布请求缺少content-type标题...

一个功能齐全的doBackground -Implementation如下所示:

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM