Google WindowsPhone HttpWebRequest vs WebClient:Post JSON data to WebService Beginners Tutorial(C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Tuesday, 13 May 2014

WindowsPhone HttpWebRequest vs WebClient:Post JSON data to WebService Beginners Tutorial(C#-XAML)

Introduction:

What is webservice?

Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language.

For example, Java can talk with Perl, Windows applications can talk with UNIX applications.and it is way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone


Why Json?

HTTP-based Web services frequently use JavaScript Object Notation (JSON) messages to return data back to the client. JSON objects can easily be instantiated in JavaScript, without parsing logic, which makes it a convenient format for messages in Web applications.


So what's this sample teach us?

Some times in our windowsphone application,we may need to request webservice in the form of Json format,then only webservice will be returns expected results.So this post is expalined about "How to post json data to webservice using HttpWebRequest or WebClient" 

So lets understand the this sample requirement :

1)I have a webservice like :

 http://test.postjson.com/Login?userid="2"&username="subbu"

here webservcie expected input parameters are userid& username with json format only ,but above service will not work,because of bad request with appending string parameters

Note: Above webservice url is taken for testing purpose only,kindly you can replace your webservice url to work with this sample.

2)Hence we need to json format request to get webservice responce
         string JsonString = "{
                                        'userid': '2',
                                        'username': 'subbu'
                                      }";
3)So we need to  request webservcie in the form of  above JsonString using HttpWebRequest/WebClient

Building the Sample:

This sample is targeted on WindowsPhone 7.1 OS.
Source file at: PostJsondataSample

Description:

1)Which one is best WebClient vs. HttpWebRequest?

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.Also WebClient doesn't have timeout property. And that's the problem, because default value is 100 seconds and that's too much to indicate if there's no Internet connection.

The main difference between the two is that WebClient is basically a wrapper around HtppWebRequest and exposes a simplified interface. 
Apart from that (at least in WP7, not sure about WP8), WebClient only works on the user thread, which is not a good thing. If you want to wait for the reply on a background thread, you need to use HttpWebRequest.

Note:Some times WebClient may not work properly if we need to handle more controls over the entire request,So in this case HttpWebRequest is good for us.


2)Which method we need to choose get vs post?


GET: 

1.All the name value pairs are submitted as a query string in URL. 
It's not secured as it is visible in plain text format in the Location bar of the web browser.
2.Length of the string is restricted. 
3.If get method is used and if the page is refreshed it would not prompt before the request is submitted again. 
4.One can store the name value pairs as bookmark and directly be used while sharing with others - example search results. 

POST: 

1. All the name value pairs are submitted in the Message Body of the request. 
2. Length of the string (amount of data submitted) is not restricted. 
3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser. 
4. If post method is used and if the page is refreshed it would prompt before the request is resubmitted. 
5. If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST. 
6. Data is submitted in the form as specified in enctype attribute of form tag and thus files can be used in FileUpload input box. 

  However in our sample we need to post json data to webservice,so that in our case we need to use post method of HttpWebRequest/WebClient.

Se lets start with two ways as following

2.1)How to post json data to webservice using HttpWebRequest post method in WindowsPhone:

Make sure HttpWebrequest object properties like
  • httpwebreqobj.ContentType = "application/json";
  • httpwebreqobj.Method="POST"

C#

private void PostJsonRequest() 
        { 
            //Please replace your webservice url here                                              string AuthServiceUri = "http://test.postjson.com/Login?"; 
            HttpWebRequest spAuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest; 
            spAuthReq.ContentType = "application/json"
            spAuthReq.Method = "POST"
            spAuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), spAuthReq); 
        } 
 
        void GetRequestStreamCallback(IAsyncResult callbackResult) 
        { 
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState; 
            Stream postStream = myRequest.EndGetRequestStream(callbackResult); 
            string postData = "{'userid': '2','username':'subbu'}"; 
            byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
            postStream.Write(byteArray, 0, byteArray.Length); 
            postStream.Close(); 
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest); 
        } 
 
        void GetResponsetStreamCallback(IAsyncResult callbackResult) 
        { 
 
            try 
            { 
                HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState; 
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult); 
                string responseString = ""; 
                Stream streamResponse = response.GetResponseStream(); 
                StreamReader reader = new StreamReader(streamResponse); 
                responseString = reader.ReadToEnd(); 
                streamResponse.Close(); 
                reader.Close(); 
                response.Close(); 
                string result = responseString; 
            } 
            catch (Exception e) 
            { 
 
            } 
        }

2.1)How to post json data to webservice using WebClient post method in WindowsPhone:

Make sure WebClient object properties like
  • webclientobj.Headers["ContentType"] = "application/json";

C#

void PostJsonRequestWebClient() 
        { 
            WebClient webclient = new WebClient(); 
            Uri uristring = null; 
           //Please replace your webservice url here                                                  uristring = new Uri("http://test.postjson.com/Login?"); 
            webclient.Headers["ContentType"] = "application/json"; 
            string WebUrlRegistration = ""; 
            string JsonStringParams = "{'userid': '2','username':'subbu'}"; 
            webclient.UploadStringCompleted += wc_UploadStringCompleted; 
           //Post data like this                                                                           webclient.UploadStringAsync(uristring, "POST", JsonStringParams); 
        } 
        private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
        { 
            try 
            { 
                 
                if (e.Result != null) 
                { 
                    string responce = e.Result.ToString(); 
                    //To Do Your functionality 
                } 
            } 
            catch 
            { 
            } 
        }
Congratulations! now you can able to post json data to webservice.

Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

16 comments:

  1. How to do a synchronous Web request??

    ReplyDelete
  2. If you want to wait asynchronously and make it as synchronous , you must use await keyword:
    So put an await in front of your async method call:
    private async void sendrequest_Click(object sender, RoutedEventArgs e)
    {
    string results = await Mywebrequestmethod();
    }

    ReplyDelete
  3. I have a DaySelector class for calendar(telerik rad control calendar and defines the data for each day in calendar)
    this class is invoked when the UI is loading.
    The class contains an overridden method whose return type is DataTemplate,
    so when I make the method async i have to make return type as Task

    which is not working!!
    I get this error

    return type must be 'System.Windows.DataTemplate' to match overridden member 'Telerik.Windows.Controls.DataTemplateSelector.SelectTemplate(object, System.Windows.DependencyObject)

    is there any way by which i can make the class return DataTemplate or I does not have to use async

    ReplyDelete
    Replies
    1. I am sorry, i am not aware of telerik rad calender control

      Delete
    2. Ok !! can you help me out with one more thing??
      I have addressed the issue here --
      https://groups.google.com/forum/#!topic/restsharp/lfVSO7nyRRY

      Delete
  4. In my case responce will be in xml format can u tell me how to convert it into Json .

    ReplyDelete
    Replies
    1. if your webservice returns xml,then why not directly parse it.Could you tell me why you are looking for convert xml reponce into json format?

      Delete
  5. How to populate the json output in list view as we needed with image

    ReplyDelete
    Replies
    1. Have you seen this post about json parsing.
      http://bsubramanyamraju.blogspot.com/2013/11/parsing-json-array-objects-in.html

      Delete
    2. Yes I read and I am able to get my json data from web but I don't know how to populate in list view as we needed like one data as title and placing hyperlink for that title and date at the bottom with small font and Image at the left and all of this I am fetching as json data..like TOI app which displays news with link and image at left

      Delete
  6. can you explain how to do json parsing in windows phone from basic steps? because i don't know about that, i am learning this concept right now

    ReplyDelete
  7. For more information on Web Development company, check out the info available online; these will help you learn to find the Website Design company.

    ReplyDelete
  8. could you please help me out with a code snippet for consuming a method in webservice which is having more than one methods in windows phone 8?

    Your help means a lot to me :)

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. your post is good but where i have to call those methods....not clear..please explain with a example like your Registration & Login page Exaple

    ReplyDelete
  11. Hello! In case you need to translate your JSON files, you can try https://poeditor.com/

    ReplyDelete

Search Engine Submission - AddMe