📜 ⬆️ ⬇️

Calling a .NET service (WCF RESTful) from an Android application

Hi Habrozhiteli!

I recently ran into a problem, it was necessary to call the .NET WCF service from Java. I found a few examples, implementations, one of them and I want to share, suddenly come in handy to someone. Walking around the Internet, I found a ready- made solution for SOAP services. Did not begin to deal with it and continued search. Then, a solution was found using the WCF RESTful service, which returned data in JSON format . I decided to understand more and try how it works.



So, first we need to write a WCF RESTful [ EN ] service. First, let's define the date contract:
Message.cs

using System.Runtime.Serialization; namespace TestService { [DataContract] public class Message { [DataMember(Order = 1)] public string Header { get; set; } [DataMember(Order =2)] public string Body { get; set; } } } 

Set the order of the elements that the web service will return via Order = x .
Then we define the service contract:
ITestService.cs

 using System.ServiceModel; using System.ServiceModel.Web; namespace TestService { [ServiceContract] public interface ITestService { [OperationContract] [WebGet(UriTemplate = "/GetMessage/?header={header}&?body={body}", ResponseFormat = WebMessageFormat.Json)] Message ComposeMessage(string header, string body); } } 

Read more about UriTemplate here .
We realize service:
TestService.svc.cs

 using System.ServiceModel.Activation; namespace TestService { public class TestService : ITestService { #region ITestService Members public Message ComposeMessage(string header, string body) { Message message = new Message() { Header = header, Body = body }; return message; } #endregion } } 

And of course, the configuration of the service:
web.config

 <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="TestService.TestService"> <endpoint binding="webHttpBinding" contract="TestService.ITestService" behaviorConfiguration="webHttp"/> </service> </services> <behaviors> <endpointBehaviors> <behavior name="webHttp"> <webHttp helpEnabled="true"/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration> 

We will deploy the service in IIS (this can be done either in Visual Studio or via IIS Manager). Create a virtual directory, let's call it TestService .
When hosted inside WCF-managed IIS, the WCF environment typically requires an .svc file indicating the type of service, as well as entries in the web.config file informing the WCF of the endpoint (binding and behaviors among other settings).

And the final touch:
TestService.svc

 <%@ ServiceHost Language="C#" Debug="true" Service="TestService.TestService" CodeBehind="TestService.svc.cs" %> 

After all actions, our virtual directory should have something like the following:

In the bin folder should be * .dll with the service.
All our service is ready. In order to test the result, in the address bar of the browser we type
localhost / TestService / TestService.svc / GetMessage /? header = Hello &? body = World
The result should look like this:
{"Header": "Hello", "Body": "World"}
This is JSON Response.
Finally, let's turn to our Android application.
I advise you to re-read this post. From it we will borrow AsyncTask implementation.
Publication of all the code does not make sense, therefore, we will “cut out” from there only the method that will parse the JSON response that came from the service. Here is his code:
 private String getMessage(String header, String body) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(_resources.getString(R.string.serviceAddress) + "/GetMessage/?header="+ header + "&?body=" + body); HttpResponse response; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); JSONObject json = new JSONObject(result); // Parsing JSONArray nameArray = json.names(); JSONArray valArray = json.toJSONArray(nameArray); _getResponse = nameArray.getString(0) + "=" + valArray.getString(0) + ", " + nameArray.getString(1) + "=" + valArray.getString(1); instream.close(); } } catch (Exception e) { _getResponse = e.getMessage(); } return _getResponse; } 

The _serviceAddress service address will be:
10.0.2.2/TestService/TestService.svc
since, when accessing localhost , we get Connection Refused IOException (who is interested, read more here ).
Also in the AndroidManifest.xml file you need to add uses-permission in order for the application to call the web service:
 <uses-permission android:name="android.permission.INTERNET" /> 

That's basically all I wanted to tell ...
')
Sources:
Lie here .

Useful links:
Thank you all for your attention!

Source: https://habr.com/ru/post/115157/


All Articles