Advertisemen
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.
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:
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)
{
}
}
}
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.
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
{
}
}
Follow me always at @Subramanyam_B Have a nice day by Subramanyam Raju :)
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
Advertisemen
Tidak ada komentar:
Posting Komentar