locked
using REST API in windows store app with c# & xaml

    Question

  • i want to learn how to use REST API with c# & xaml in windows store apps, can any one provide me a good book on this ?
    Thursday, June 19, 2014 3:52 AM

All replies

  • I'm not sure which books cover this well, but you can start with the documentation at Connecting to web services and the HttpClient Sample .

    --Rob

    Thursday, June 19, 2014 4:20 AM
    Owner
  • public class RestServiceClient
        {
            private const string JSON_MIMETYPE = "application/json;odata=verbose";
    
            public RestServiceClient()
            {
                CreateHttpClient();
                RootFilter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            }
    
            public RestServiceClient(IEnumerable<Tuple<string, string>> headers)
                : this()
            {
                foreach (var header in headers)
                    Client.DefaultRequestHeaders.Add(header.Item1, header.Item2);
            }
    
            protected HttpBaseProtocolFilter RootFilter { get; set; }
    
            protected HttpClient Client { get; set; }
    
            public virtual Task<TResponse> DoRestRequest<TRequest, TResponse>(HttpMethod method, Uri uri)
                where TRequest : class
            {
                return this.DoRestRequest<TRequest, TResponse>(method, uri, null, null);
            }
    
            public async virtual Task<TResponse> DoRestRequest<TRequest, TResponse>(HttpMethod method, Uri uri, TRequest requestData, IEnumerable<Tuple<string, string>> headers = null)
                where TRequest : class
            {
    
                var list = headers != null ? headers.ToList() : new List<Tuple<string, string>>();
                list.Add(new Tuple<string, string>("Accept", JSON_MIMETYPE));
    
                IHttpContent content = null;
                if (requestData != null)
                {
                    var data = Serialize(requestData);
    
                    var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                    await stream.WriteAsync(data.AsBuffer()).AsTask().ConfigureAwait(false);
                    stream.Seek(0);
    
    #warning todo
                    // this feels stupid
                    StreamReader reader = new StreamReader(new MemoryStream(data));
                    string jsondata = reader.ReadToEnd();
    
                    var requestContent = content = new HttpStreamContent(stream);
                    requestContent.Headers["Content-Type"] = JSON_MIMETYPE;
                }
    
                var responseStream = await DoRequest(method, uri, content, list);
    
                return Deserialize<TResponse>(responseStream.AsStreamForRead());
            }
    
            public async virtual Task<IInputStream> DoRequest(HttpMethod method, Uri uri, IHttpContent content = null, IEnumerable<Tuple<string, string>> headers = null)
            {
                HttpRequestMessage message = new HttpRequestMessage(method, uri)
                {
                    Content = content,
                };
    
                if (headers != null)
                {
                    foreach (var header in headers)
                        message.Headers[header.Item1] = header.Item2;
                }
    
                var response = await Client.SendRequestAsync(message).AsTask().ConfigureAwait(false);
                if (response.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new UnauthorizedException();
                }
                response.EnsureSuccessStatusCode();
    
                var responseStream = await response.Content.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false);
                return responseStream;
            }
    
            protected byte[] Serialize(object requestData)
            {
                using (var memoryStream = new MemoryStream())
                {
                    StreamWriter writer = new StreamWriter(memoryStream);
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, requestData);
                    writer.Flush();
    
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    byte[] buf = new byte[memoryStream.Length];
                    memoryStream.Read(buf, 0, buf.Length);
    
                    return buf;
                }
            }
    
            protected TResult Deserialize<TResult>(Stream stream)
            {
                JsonTextReader reader = new JsonTextReader(new StreamReader(stream));
                JsonSerializer serializer = new JsonSerializer();
                return serializer.Deserialize<TResult>(reader);
            }
    
            protected virtual HttpClient CreateHttpClient()
            {
                return Client = new HttpClient(CreateFilter());
            }
    
            protected virtual IHttpFilter CreateFilter()
            {
                return RootFilter = new HttpBaseProtocolFilter();
            }
        }

    this is a base class i use for my webservices;

    it helps me doing the requests and handling the serialization


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    Thursday, June 19, 2014 7:04 AM
  • is this base class is enough to handle any kind of webservice??
    Friday, June 20, 2014 1:03 PM
  • i want to connect to a https server to query its database using REST api , i want to recieve the results in json format & deserialize them in to string, can any one help me to achieve this or provide a small code sample for windows 8?  
    Friday, July 18, 2014 5:57 AM
  • Hi,

    i have this class:

    public class RestServiceClient
        {
            private const string JSON_MIMETYPE = "application/json;odata=verbose";
    
            protected HttpBaseProtocolFilter RootFilter { get; set; }
    
            protected HttpClient Client { get; set; }
    
            public virtual Task<TResponse> DoRestRequest<TRequest, TResponse>(HttpMethod method, Uri uri)
                where TRequest : class
            {
                return this.DoRestRequest<TRequest, TResponse>(method, uri, null, null);
            }
    
            public async virtual Task<TResponse> DoRestRequest<TRequest, TResponse>(HttpMethod method, Uri uri, TRequest requestData, IEnumerable<Tuple<string, string>> headers = null)
                where TRequest : class
            {
    
                var list = headers != null ? headers.ToList() : new List<Tuple<string, string>>();
                list.Add(new Tuple<string, string>("Accept", JSON_MIMETYPE));
    
                IHttpContent content = null;
                if (requestData != null)
                {
                    var data = Serialize(requestData);
    
                    var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                    await stream.WriteAsync(data.AsBuffer()).AsTask().ConfigureAwait(false);
                    stream.Seek(0);
    
    #warning todo
                    // this feels stupid
                    StreamReader reader = new StreamReader(new MemoryStream(data));
                    string jsondata = reader.ReadToEnd();
    
                    var requestContent = content = new HttpStringContent(jsondata);
                    requestContent.Headers["Content-Type"] = JSON_MIMETYPE;
                }
    
                var responseStream = await DoRequest(method, uri, content, list);
    
                return Deserialize<TResponse>(responseStream.AsStreamForRead());
            }
    
            public async virtual Task<IInputStream> DoRequest(HttpMethod method, Uri uri, IHttpContent content = null, IEnumerable<Tuple<string, string>> headers = null)
            {
                HttpRequestMessage message = new HttpRequestMessage(method, uri)
                {
                    Content = content,
                };
    
                if (headers != null)
                {
                    foreach (var header in headers)
                        message.Headers[header.Item1] = header.Item2;
                }
    
                var response = await Client.SendRequestAsync(message).AsTask().ConfigureAwait(false);
                if (response.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new UnauthorizedException();
                }
                response.EnsureSuccessStatusCode();
    
                var responseStream = await response.Content.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false);
                return responseStream;
            }
    
            protected byte[] Serialize(object requestData)
            {
                using (var memoryStream = new MemoryStream())
                {
                    StreamWriter writer = new StreamWriter(memoryStream);
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, requestData);
                    writer.Flush();
    
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    byte[] buf = new byte[memoryStream.Length];
                    memoryStream.Read(buf, 0, buf.Length);
    
                    return buf;
                }
            }
    
            protected TResult Deserialize<TResult>(Stream stream)
            {
                JsonTextReader reader = new JsonTextReader(new StreamReader(stream));
                JsonSerializer serializer = new JsonSerializer();
                return serializer.Deserialize<TResult>(reader);
            }
    
            protected virtual HttpClient CreateHttpClient()
            {
                return Client = new HttpClient(CreateFilter());
            }
    
            protected virtual IHttpFilter CreateFilter()
            {
                return RootFilter = new HttpBaseProtocolFilter();
            }
        }

    to do a get on a rest url i write extension method:

    public static class RestServiceExtensions
        {
            public async Task<MyObject> GetDataAsync(this RestServiceClient client)
            {
                return client.DoRestRequest<object, MyObject>(HttpMethod.Get, new Uri(""));
            }
    
            public async Task<MyObject> GetDataAsync(this RestServiceClient client, MyObject postdata)
            {
                return client.DoRestRequest<MyObject, MyObject>(HttpMethod.Post, new Uri(""), postdata);
            }
        }

    it doesnt really matter if you have http or https


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    Friday, July 18, 2014 6:51 AM
  • thanx dave, but do i need this entire class to implement a simple GET method in my application ?? 
    Friday, July 18, 2014 2:04 PM
  • Hi kranthi,

    you can try with this code 

    HttpClient client = new HttpClient();
    string url = "http://yourservice.com/some/resource";
    HttpResponseMessage response = await client.GetAsync(url);
    return response.Content.ReadAsString();

    this simpale way to call Rest Api Get Method.

    thanks

    pramod


    prmdpandit

    • Proposed as answer by pramod pandit Thursday, July 24, 2014 6:17 AM
    Friday, July 18, 2014 2:26 PM
  • try to look on this http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx

    http client is your way to handle  REST API it's too easy just try this 

    var client=new HttpClient();
    
    var response = await client.GetAsync("source url");
    
    var jsonstring=response.Content.ReadAsString();
    
    //handel json data for example


    Friday, July 18, 2014 3:34 PM
  • thanx for the minified version pramod but the server is returning the response in json format , how can i capture the json data & deserialize it to text format?
    Friday, July 18, 2014 3:40 PM
  • Hi Kranthi & Aly,

    Please read the thread before responding.

    For new code you should use Windows.Web.HttpClient, not System.Net.Http.HttpClient. This was mentioned and documentation and samples provided previously ( How to connect to an HTTP server using Windows.Web.Http )

    You can use the Windows.Data.Json classes to parse the JSON returned.

    --Rob

    Friday, July 18, 2014 10:20 PM
    Owner
  • First Thanks Rob Caplan

    Kranthi you still can use same code with Windows.Web.HttpClient 

    and this an example to deserialize json with Json.Net http://james.newtonking.com/json

    var client=new HttpClient();
    
    var response = await client.GetAsync("source url");
    
    var jsonstring=response.Content.ReadAsString();
    
    //handel json data for example
    YourDataModel m = JsonConvert.DeserializeObject<List<YourDataModel>>(jsonstring);


     
    Saturday, July 19, 2014 2:49 AM
  • the example given in the link provided is for visual studio 2013, but i want the sample for visual studio 2012 as i want to build windows 8 app not 8.1  
    Saturday, July 19, 2014 6:09 AM
  • hello kranthi,

    return response.Content.ReadAsString();

    after get your json data in string you have to parse your jsonstring here the code.

    list<Model> modellist=new list<model>();

    var jsonpars=JsonArray.Parse(jsonstring);

    foreach(var item in jsonpars);
    {
    var obj=item.getobject();
    model m=new model();//Your properties model class object
    m.title=item.GetObject().GetNamedString"Title");

    modellist.add(m);
    }

    i hope this useful for you .

    thanks

    pramod


    prmdpandit

    • Proposed as answer by pramod pandit Thursday, July 24, 2014 6:59 AM
    Thursday, July 24, 2014 6:59 AM
  • still i am not getting the desired results pramod, the below is my code.

    private async void datason(object sender, RoutedEventArgs e)
            {
                var url="https://mywebapi.net/?j=4";
                var client = new HttpClient();
                var response = await client.GetAsync(url);
                var jsonstring = response.Content.ReadAsStringAsync();
                List<string> output = new List<string>();
                var jsonpars = JsonArray.Parse(await jsonstring);
                mybox.Text = jsonstring.ToString();
                foreach (var item in jsonpars)
                {
                    var obj = item.GetObject();
                }
               
                
            }

    Thursday, July 24, 2014 11:59 AM
  • Hello Kranthi,

    after getting json string and convert in jsonarray

     var jsonpars = JsonArray.Parse(await jsonstring);// json array

    foreach (var item in jsonpars)
                {
                    var obj = item.Getnumber();// if data valutype is number or you can use Getstring also;

                }

    bleow I have give the example of jsonstring to json array after getting values .

    JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
        double width = jsonValue.GetObject().GetNamedNumber("Width");
        double height = jsonValue.GetObject().GetNamedNumber("Height");
        string title = jsonValue.GetObject().GetNamedString("Title");
        JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
        foreach (var item in ids)
        {
            var obj = item.GetNumber();
        }

    I hope it will help you, if you have some issue you can send me your jsonstring

    its very much help me to solve your problem.

    thanks

    pramod


    prmdpandit

    • Proposed as answer by pramod pandit Friday, July 25, 2014 6:42 AM
    Friday, July 25, 2014 6:40 AM
  • hii pramod , this is my json string

    {
        "found": "true", 
        "items": [
            {
                "name": "papaya", 
                "name": "mango"
            }
        ], 
        "time": "0.245", 
        "type": "fruits"
    }
    Friday, July 25, 2014 12:57 PM
  • its working fine for my service.

    thanks

    Thursday, September 11, 2014 2:28 PM