This sample shows how to consume a web service method from F# by simply posting the parameters as a query string.
Below is the F# code to consume a web method called GetNthPrime which takes a parameter index (0 based) and returns the prime number at that index:
open System.Text
open System.Net
open System.IO
open System.Xml
/// Returns response of HTTP post
let HttpPost (url:string) (postData:string) =
let request = WebRequest.Create(url) in
request.Method <- WebRequestMethods.Http.Post;
request.ContentType <- "application/x-www-form-urlencoded";
let bytes = Encoding.ASCII.GetBytes(postData) in
request.ContentLength <- Int64.of_int bytes.Length;
let stream = request.GetRequestStream() in
stream.Write(bytes,0,bytes.Length);
stream.Close();
let response = request.GetResponse( ) in
let reader = new StreamReader( response.GetResponseStream() ) in
reader.ReadToEnd()
/// Reads Nth Prime from web service
let GetNthPrime n =
let queryString = (sprintf "index=%d" n) in
let url = "http://localhost/Prime/service.asmx/GetNthPrime" in
let response = HttpPost url queryString in
System.Diagnostics.Debug.WriteLine( response );
// Read (XML) HTTP response
let reader = new XmlTextReader( new StringReader(response) ) in
ignore( reader.Read() );
ignore( reader.Read() );
ignore( reader.Read() );
let result = reader.ReadElementContentAsInt() in
result
do let prime = GetNthPrime 2 in System.Diagnostics.Debug.WriteLine(prime)
The following code fragment represents the C# web service's web method to consume; from Visual Studio create a new web service project in a virtual directory called Prime and replace the generated example method with this:
[WebMethod]
public int GetNthPrime(int index)
{
int value = 2;
int i = 0;
while (i < index)
{
++value;
++i;
while (!IsPrime(value)) ++value;
}
return value;
}
private static bool IsPrime(int value)
{
int end = (int)Math.Ceiling(Math.Sqrt((double)value));
for (int i = 2; i <= end; i++)
{
if (value % i == 0) return false;
}
return true;
}