如何使用 Android 使用 WCF 服务 [英] How to Consume WCF Service with Android

查看:28
本文介绍了如何使用 Android 使用 WCF 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在java中我编写了以下方法:

private void Login(){HttpClient httpClient = new DefaultHttpClient();尝试{String url = "http://192.168.1.5:8000/Login?username=test&password=test";HttpGet 方法 = new HttpGet( new URI(url) );HttpResponse 响应 = httpClient.execute(method);如果(响应!= null){Log.i("登录", "收到" + getResponse(response.getEntity()));}别的{Log.i("登录","得到一个空响应");}} catch (IOException e) {Log.e("错误", e.getMessage());} catch (URISyntaxException e) {Log.e("错误", e.getMessage());}}私有字符串 getResponse( HttpEntity 实体){字符串响应 = "";尝试{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);}响应 = sb.toString();isr.close();} 捕捉(IOException ioe){ioe.printStackTrace();}返回响应;}

但在服务器端,到目前为止我还没有弄清楚.

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

谢谢!

解决方案

要开始使用 WCF,对于 Web 服务绑定使用默认的 SOAP 格式和 HTTP POST(而不是 GET)可能是最简单的.最简单的 HTTP 绑定是basicHttpBinding".以下是您的登录服务的 ServiceContract/OperationContract 可能是什么样子的示例:

[ServiceContract(Namespace="http://mycompany.com/LoginService")]公共接口 ILoginService{【经营合同】字符串登录(字符串用户名,字符串密码);}

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

公共类 LoginService : ILoginService{公共字符串登录(字符串用户名,字符串密码){//用用户名、密码做一些事情来获取/创建 sessionId//字符串 sessionId = "12345678";字符串 sessionId = OperationContext.Current.SessionId;返回 sessionId;}}

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

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

<主机><基地址><add baseAddress="http://somesite.com:55555/LoginService/"/></baseAddresses></host><端点名称="登录服务"地址=""绑定=基本HttpBinding"contract="WcfTest.ILoginService"/><端点名称="LoginServiceMex"地址=墨西哥"绑定=mexHttpBinding"合同=IMetadataExchange"/></服务></服务></system.serviceModel></配置>

(MEX 的东西在生产环境中是可选的,但在使用 WcfTestClient.exe 进行测试和暴露服务元数据时需要).

您必须修改 Java 代码才能向服务发布 SOAP 消息.在与非 WCF 客户端互操作时,WCF 可能有点挑剔,因此您必须稍微弄乱 POST 标头才能使其工作.运行此程序后,您就可以开始调查登录的安全性(可能需要使用不同的绑定来获得更好的安全性),或者可能使用 WCF REST 来允许使用 GET 而不是 SOAP/POST 登录.

以下是 Java 代码中 HTTP POST 应该是什么样子的示例.有一个名为Fiddler"的工具对于调试网络服务非常有用.

POST/LoginService HTTP/1.1内容类型:文本/xml;字符集=utf-8SOAPAction:http://mycompany.com/LoginService/ILoginService/Login"主机:somesite.com:55555内容长度:216期望:100-继续连接:保持活动<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:身体><登录xmlns="http://mycompany.com/LoginService"><用户名>废话</用户名><password>Blah2</password></登录></s:身体></s:信封>

I am creating a server in .NET and a client application for Android. I would like to implement an authentication method which sends username and password to server and a server sends back a session string.

I'm not familiar with WCF so I would really appreciate your help.

In java I've written the following method:

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

But on the server side so far I haven't figured out anything.

I would be really thankful if anyone could explain how to create an appropriate method string Login(string username, string password) with appropriate App.config settings and Interface with appropriate [OperationContract] signature in order to read these two parameters from client and reply with session string.

Thanks!

解决方案

To get started with WCF, it might be easiest to just use the default SOAP format and HTTP POST (rather than GET) for the web-service bindings. The easiest HTTP binding to get working is "basicHttpBinding". Here is an example of what the ServiceContract/OperationContract might look like for your login service:

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

The implementation of the service could look like this:

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

You can host this as a windows service using a ServiceHost, or you can host it in IIS like a normal ASP.NET web (service) application. There are a lot of tutorials out there for both of these.

The WCF service config might look like this:

<?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>

(The MEX stuff is optional for production, but is needed for testing with WcfTestClient.exe, and for exposing the service meta-data).

You'll have to modify your Java code to POST a SOAP message to the service. WCF can be a little picky when inter-operating with non-WCF clients, so you'll have to mess with the POST headers a little to get it to work. Once you get this running, you can then start to investigate security for the login (might need to use a different binding to get better security), or possibly using WCF REST to allow for logins with a GET rather than SOAP/POST.

Here is an example of what the HTTP POST should look like from the Java code. There is a tool called "Fiddler" that can be really useful for debugging web-services.

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>

这篇关于如何使用 Android 使用 WCF 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆