使用Android消费WCF服务

3

我在一个WCF服务中有以下代码,它返回一个字符串,我想在Android应用程序中使用它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace HelloService
{
    public class HelloService : IHelloService
    {
        public string SayHello()
        {
            return "Bonjuor Android from WCF Service";
        }
    }
}

我有两个问题:

1、由于try catch块,我不确定自己是否接近Java。如果我在代码中添加它们,应用程序可以正常工作但无法在toast或text view中显示文本;如果我不加try catch块,则Eclipse会提示我修复问题并添加一个try catch块... 哈哈。

2、我不知道自己在干什么。

@Override
public void onCreate(Bundle icicle)
{
    super.onCreate(icicle);
    setContentView(R.layout.contacts);               

try 
{

        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri = new URI("http://www.themorningtonpeninsula.com/HelloService/HelloService.svc"); 

        HttpGet httpget = new HttpGet(uri + "/SayHello");
        httpget.setHeader("Accept", "application/json");
        httpget.setHeader("Content-type", "application/json; charset=utf-8");

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity responseEntity = response.getEntity();

        long intCount = responseEntity.getContentLength();

        char[] buffer = new char[(int)intCount];
        InputStream stream = responseEntity.getContent();
        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
        try
        {
                reader.read(buffer);
                String str = new String(buffer);
                TextView thetext = new TextView(this);
                thetext.setText(str);
                setContentView(thetext);
                Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            }

            catch (IOException e) 
            {
                e.printStackTrace();
            }
            stream.close();

        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    } 
}

能否有人看一下这段代码,告诉我是否接近正确,或者更好的是指导我,或者发布一些可行的代码?

2个回答

3
所有问题都已解决,Java代码运行良好,问题出在我的WCF服务上。它没有正确传递格式化的JSON对象。所以我回去找了一个简单明了的教程,直到找到这个。对作者表示赞扬。 http://www.codeproject.com/KB/WCF/RestServiceAPI.aspx 祝好,
Mike.

0

我认为你应该使用另一个线程来执行网络任务,同时你可以使用runOnUiThread()方法来更新UI,比如显示Toast等。


我不太确定你的意思,因为我说这对我来说是新的,只是在网上搜索,对大多数人来说都是新的。你是说我应该先加载数据,然后再使用它,而不是同时尝试加载和使用它吗??? 我能够在模拟器上以未格式化的HTML形式获取默认的“您已创建了一个服务。”页面,但在手机上却不能,所以我从WCF服务中得到了一些东西。 - user903601
我认为你仍然应该尝试从另一个线程获取Web服务数据,然后只需检查它是什么Web服务回复。 - Anup Rojekar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接