我在一个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();
}
}
}
能否有人看一下这段代码,告诉我是否接近正确,或者更好的是指导我,或者发布一些可行的代码?