如何使用 Android 使用 WCF 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/669764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:23:26  来源:igfitidea点击:

How to Consume WCF Service with Android

.netandroidwcfrest

提问by Niko Gamulin

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.

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

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

我不熟悉 WCF,因此非常感谢您的帮助。

In java I've written the following method:

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

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.

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

Thanks!

谢谢!

采纳答案by Andy White

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:

要开始使用 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);
}

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.

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

The WCF service config might look like this:

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>

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

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

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.

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

以下是 Java 代码中 HTTP POST 应该是什么样子的示例。有一个名为“ 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>

回答by Andy White

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

另一种选择可能是完全避免 WCF,而只使用 .NET HttpHandler。HttpHandler 可以从您的 GET 中获取查询字符串变量,然后将响应写回 Java 代码。

回答by Jonathan Parker

You will need something more that a http request to interact with a WCF service UNLESS your WCF service has a REST interface. Either look for a SOAP web service API that runs on android or make your service RESTful. You will need .NET 3.5 SP1 to do WCF REST services:

除非您的 WCF 服务具有 REST 接口,否则您将需要更多的东西来与 WCF 服务交互的 http 请求。要么寻找在 android 上运行的 SOAP Web 服务 API,要么使您的服务成为 RESTful。您将需要 .NET 3.5 SP1 来执行 WCF REST 服务:

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

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

回答by Necronet

From my recent experience i would recommend ksoaplibrary to consume a Soap WCF Service, its actually really easy, this anddev threadmigh help you out too.

根据我最近的经验,我会推荐ksoap库来使用 Soap WCF 服务,它实际上非常简单,这个和开发线程也可以帮助你。

回答by Cheeso

If I were doing this I would probably use WCF REST on the server and a REST libraryon the Java/Android client.

如果我这样做,我可能会在服务器上使用 WCF REST ,在 Java/Android 客户端上使用REST 库