如何使用Android消耗WCF服务

Nik*_*lin 77 .net rest wcf android

我正在用.NET创建服务器和Android的客户端应用程序.我想实现一个身份验证方法,它将用户名和密码发送到服务器,服务器发回一个会话字符串.

我不熟悉WCF,所以我非常感谢你的帮助.

在java中我写了以下方法:

private void Login()
{
  HttpClient httpClient = new DefaultHttpClient();
  try
  {
      String url = "http://192.168.1.5:8000/Login?username=test&password=test";

    HttpGet method = new HttpGet( new URI(url) );
    HttpResponse response = httpClient.execute(method);
    if ( response != null )
    {
      Log.i( "login", "received " + getResponse(response.getEntity()) );
    }
    else
    {
      Log.i( "login", "got a null response" );
    }
  } catch (IOException e) {
    Log.e( "error", e.getMessage() );
  } catch (URISyntaxException e) {
    Log.e( "error", e.getMessage() );
  }
}

private String getResponse( HttpEntity entity )
{
  String response = "";

  try
  {
    int length = ( int ) entity.getContentLength();
    StringBuffer sb = new StringBuffer( length );
    InputStreamReader isr = new InputStreamReader( entity.getContent(), "UTF-8" );
    char buff[] = new char[length];
    int cnt;
    while ( ( cnt = isr.read( buff, 0, length - 1 ) ) > 0 )
    {
      sb.append( buff, 0, cnt );
    }

      response = sb.toString();
      isr.close();
  } catch ( IOException ioe ) {
    ioe.printStackTrace();
  }

  return response;
}
Run Code Online (Sandbox Code Playgroud)

但到目前为止,在服务器端我还没有想到任何东西.

如果有人能解释如何创建一个合适的方法字符串Login(字符串用户名,字符串密码)和适当的App.config设置以及具有相应[OperationContract]签名的接口,以便从客户端读取这两个参数并回复,我将非常感激.会话字符串.

谢谢!

And*_*ite 41

要开始使用WCF,最简单的方法是使用默认的SOAP格式和HTTP POST(而不是GET)来进行Web服务绑定.最简单的HTTP绑定是"basicHttpBinding".以下是ServiceContract/OperationContract对您的登录服务的外观示例:

[ServiceContract(Namespace="http://mycompany.com/LoginService")]
public interface ILoginService
{
    [OperationContract]
    string Login(string username, string password);
}
Run Code Online (Sandbox Code Playgroud)

服务的实现可能如下所示:

public class LoginService : ILoginService
{
    public string Login(string username, string password)
    {
        // Do something with username, password to get/create sessionId
        // string sessionId = "12345678";
        string sessionId = OperationContext.Current.SessionId;

        return sessionId;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用ServiceHost将其作为Windows服务托管,也可以像在普通的ASP.NET Web(服务)应用程序中一样在IIS中托管它.这两个教程都有很多教程.

WCF服务配置可能如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>


    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="LoginServiceBehavior">
                    <serviceMetadata />
                </behavior>
            </serviceBehaviors>
        </behaviors>

        <services>
            <service name="WcfTest.LoginService"
                     behaviorConfiguration="LoginServiceBehavior" >
                <host>
                    <baseAddresses>
                        <add baseAddress="http://somesite.com:55555/LoginService/" />
                    </baseAddresses>
                </host>
                <endpoint name="LoginService"
                          address=""
                          binding="basicHttpBinding"
                          contract="WcfTest.ILoginService" />

                <endpoint name="LoginServiceMex"
                          address="mex"
                          binding="mexHttpBinding"
                          contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
</configuration>
Run Code Online (Sandbox Code Playgroud)

(MEX的东西对于生产是可选的,但是需要使用WcfTestClient.exe进行测试,以及用于公开服务元数据).

您必须修改Java代码以将SOAP消息POST到服务.在与非WCF客户端进行交互操作时,WCF可能会有点挑剔,因此您必须稍微弄乱POST头文件才能使其工作.一旦运行,您就可以开始研究登录的安全性(可能需要使用不同的绑定来获得更好的安全性),或者可能使用WCF REST来允许使用GET而不是SOAP/POST进行登录.

以下是HTTP代码应该从Java代码中看起来的示例.有一个名为" Fiddler " 的工具,对于调试Web服务非常有用.

POST /LoginService HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://mycompany.com/LoginService/ILoginService/Login"
Host: somesite.com:55555
Content-Length: 216
Expect: 100-continue
Connection: Keep-Alive

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Login xmlns="http://mycompany.com/LoginService">
<username>Blah</username>
<password>Blah2</password>
</Login>
</s:Body>
</s:Envelope>
Run Code Online (Sandbox Code Playgroud)

  • 是的,我现在也会推荐REST,这个答案来自几年前REST/JSON不像现在那样流行. (4认同)

And*_*ite 7

另一个选择可能是避免WCF全部在一起,只使用.NET HttpHandler.HttpHandler可以从GET中获取查询字符串变量,并只回写对Java代码的响应.

  • 你可以做到这一点,但没有适当的框架,感觉这将是脆弱的,难以维护.您如何向客户端记录REST接口?如果你想要JSON怎么办?等等 (6认同)

Jon*_*ker 6

除了您的WCF服务具有REST接口之外,您将需要更多的http请求与WCF服务进行交互.要么寻找在Android上运行的SOAP Web服务API,要么使您的服务RESTful.您将需要.NET 3.5 SP1来执行WCF REST服务:

http://msdn.microsoft.com/en-us/netframework/dd547388.aspx