在Android应用中使用WCF服务

时间:2012-11-08 12:18:00

标签: android wcf web-services networking

我正在尝试在Android中使用以下WCF网络服务

这是我的代码

服务

ILoginService

    [ServiceContract]
    public interface ILoginService
    {
        [OperationContract]
        bool LoginUser(string uname, string password);
    }

LoginService.svc.cs

  public class LoginService : ILoginService
    {
        public bool LoginUser(string uname, string password)
        {
            if (uname == password)
                return true;
            else
                return false;
        }
    }

web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

      <services>
        <service name="LoginService.LoginService">
          <endpoint binding="basicHttpBinding" contract="LoginService.ILoginService" ></endpoint>  
      </service>
      </services>

      <behaviors>
      <serviceBehaviors>
        <behavior>

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

  <system.webServer>
    <defaultDocument>
       <files>
        <clear />
        <add value="LoginService.svc" />
      </files>
    </defaultDocument>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
   <handlers>
      <add name="svc-ISAPI-2.0" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="File" preCondition="classicMode,runtimeVersionv4.0,bitness32"/>
      <add name="svc-Integrated" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler" resourceType="File" preCondition="integratedMode"/>
    </handlers>
  </system.webServer>

</configuration>

我已在IIS上托管此服务,并且非常适合dotnet应用程序。 我用于访问此服务的android代码是

     private void callServiceMethod() throws IOException, XmlPullParserException 
     {
        String NAMESPACE = "http://tempuri.org/";
        String METHOD_NAME = "LoginUser";
        String SOAP_ACTION = "http://tempuri.org/LoginUser";
        String URL = "http://192.168.16.61/LoginService/LoginService.svc";

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

        PropertyInfo pi = new PropertyInfo();
        pi.setName("uname");
        pi.setValue("jayant");
        pi.setType(String.class);

        Request.addProperty(pi);

        PropertyInfo pi2 = new PropertyInfo();
        pi2.setName("password");
        pi2.setValue("jayant");
        pi2.setType(String.class);
        Request.addProperty(pi2);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);
        AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
        androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapObject response = (SoapObject)envelope.getResponse();
        Result =  Boolean.parseBoolean(response.getProperty(0).toString()) ;
    }

在运行此代码时,我的程序提供异常: XmlpullParserException:期望结束标记

请告诉我我在哪里做错了? 感谢

2 个答案:

答案 0 :(得分:0)

试试这个

public InputStream getResponse(String url,String params)
{
    InputStream is = null;
    try
    {

        HttpPost request = new HttpPost(url);
        request.setHeader("Accept", "application/xml");
        request.setHeader("Content-type", "application/xml");
        StringEntity entity = new StringEntity(params.toString());
        request.setEntity(entity);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);

        String ss1=EntityUtils.toString(response.getEntity());

        Log.v("log", ss1);

        is = new ByteArrayInputStream(ss1.getBytes("UTF-8"));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return is;
}

传递url http:XXXXXXXXX / LoginService / LoginService.svc / LoginUser 和params是XML body作为字符串 并在XML解析中传递inputStream

答案 1 :(得分:0)

您需要为操作合同指定一些属性。 尝试这样的事情:

    [OperationContract()]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/LoginUser?uname={username}&password={password})]
bool LoginUser(string uname, string password);

确保您不使用WebMessageBodyStyle.Bare,因为这会将不必要的文本添加到您的XML中。

还要考虑在您的WCF服务中使用JSON,因为JSON更轻,并且内置于Android。 JSON Homepage除了在.NET 4 +中添加JSON功能外,还很容易。