Push an variable into a method - c#

I have an httpWebRequest to access an XML and save it locally then read it and show it to the screen. Problem is, i have to do this for more than one "pivot item", and the method that saves the xml is
private static void GetResponseCallback(IAsyncResult asynchronousResult)
and doesn't support adding a new variable to it so i can dynamically name the xml ("tmp"+xmlName+".xml") .
So the question is: How do i push a variable in the xml name ?
public class HttpWebReqMethod
{
public void httpRequestMethod (string url, string xmlName)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpRequest);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = httpRequest.EndGetRequestStream(asynchronousResult);
string postData = "";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
httpRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), httpRequest);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseStream = streamRead.ReadToEnd();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var istream = new IsolatedStorageFileStream(#"tmp" + xmlName + ".xml", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(istream))
{
sw.Write(responseStream);
}
}
}
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}

Here are two things you could do:
make GetResponseCallback not static, and store the xmlName in an instance variable
pass a state object (anything that has a property named xmlName, and something else to identify it by) to the request, and you can get it from the AsyncState
change GetResponseCallback's function to the following, and make the whole thing a callback "factory"
private static AsyncCallback GetResponseCallback(string xmlName)
{
return (IAsyncResult asynchronousResult) =>{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseStream = streamRead.ReadToEnd();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var istream = new IsolatedStorageFileStream(#"tmp" + xmlName + ".xml", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(istream))
{
sw.Write(responseStream);
}
}
}
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
}
EDIT to ADD:
the usage then changes to
httpRequest.BeginGetRequestStream(GetRequestStreamCallback(xmlName), httpRequest);

It's a callback method which is mapped to a specific delegate type, so no, you can't amend it's signature.
One option to resolve this would be to have a separate class such as this:
class HttpRequestState {
HttpWebRequest httpWebRequest;
string xmlFileName;
}
You can then set an instance of that class as the state object when you run the Begin callback:
httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpRequest);
would change to
httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), new HttpRequestState() { httpWebRequest = httpRequest; xmlFileName = "tmp"+xmlName+".xml" });
Then of course, you can pull out the xmlFileName and the httpWebRequest like this:
HttpRequestState stateObj = (HttpRequestState)asynchronousResult.AsyncState;
HttpWebRequest httpRequest = stateObj.httpWebRequest;
string fileName = xmlFileName;

Related

Retrieve response and do an action in a HttpWebRespo call, from an IAsyncResult function C#

From my class I call another class that makes a call to an API with an IAsyncResult function that listens when the server responds.
My question is how do I go about when the API responds, take that response and do an action.
My code listens, and grabs the answer, but I'm not managing to do anything with it
winForm.cs:
var response = services.postService(payment,url);
//if response Its OK make somthing
service.cs
public HttpWebRequest request;
private static ManualResetEvent allDone = new ManualResetEvent(false);
public void postService(PayModel paymentObject, String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "pay");
request.ContentType = "application/json";
request.Method = "POST";
var response = request.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, paymentObject)), request);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult,PayModel paymentObject)
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var streamWriter = new StreamWriter(request.EndGetRequestStream(asynchronousResult)))
{
string json = new JavaScriptSerializer().Serialize(paymentObject);
Console.Out.WriteLine(json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var response = request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
streamResponse.Close();
streamRead.Close();
response.Close();
allDone.Set();
frmVenta.closeTransaccion();
}
I tried many things but I can't get the answer, when I put a return on it, it never performs the action, the program continues and does not return
I cant use HttpClient , the program es older.

Sending HTTP POST Request with XML to a web service and reading response data in C# for windows 8 phone

I a newbie at windows 8 phone development. I want to send an aync HTTP POST Request to a PHP web service with some headers and XML in the request body.
Also, I want to read the response sent back by the PHP web service.
Please guide me, how can I achieve the above two stated things.
what I have tried until now i am giving below
// Main begins program execution.
public static void SendRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers["SOURCE"] = "WinApp";
var response = await httpRequest(webRequest);
}
public static async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
MessageBox.Show(received.ToString());
}
}
}
return received;
}
I am able to send the request using the above code. I just need to know that how I can send the XML in the request body to my web service.
For Set a file, and receive a server Response, I use that for sending .csv files:
First I initialize a POST Request:
/// <summary>
/// Initialize the POST HTTP request.
/// </summary>
public void SentPostReport()
{
string url = "http://MyUrlPerso.com/";
Uri uri = new Uri(url);
// Create a boundary for HTTP request.
Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + Boundary;
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), est);
allDone.WaitOne();
}
After initialized Request, I send the differents parts of my files (headers + content + footer).
/// <summary>
/// Send a File with initialized request.
/// </summary>
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
string contentType = "binary";
string myFileContent = "one;two;three;four;five;"; // CSV content.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream memStream = request.EndGetRequestStream(asynchronousResult);
byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "\r\n");
memStream.Write(boundarybytes, 0, boundarybytes.Length);
// Send headers.
string headerTemplate = "Content-Disposition: form-data; ";
headerTemplate += "name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: " + contentType + "\r\n\r\n";
string fileName = "MyFileName.csv";
string header = string.Format(headerTemplate, "file", fileName);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
byte[] contentbytes = System.Text.Encoding.UTF8.GetBytes(myFileContent);
// send the content of the file.
memStream.Write(contentbytes, 0, contentbytes.Length);
// Send last boudary of the file ( the footer) for specify post request is finish.
byte[] boundarybytesend = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "--\r\n");
memStream.Write(boundarybytesend, 0, boundarybytesend.Length);
memStream.Flush();
memStream.Close();
allDone.Set();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
And, Finnaly, I get The response server response, indicate the file is transmetted.
/// <summary>
/// Get the Response server.
/// </summary>
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd(); // this is a response server.
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
// error.
}
}
This sample works on Windows Phone 7 and Windows Phone 8.
This is for send a .csv content. You can adapt this code for send Xml content.
Replace just
string myFileContent = "one;two;three;four;five;"; // CSV content.
string fileName = "MyFileName.csv";
by your XML
string myFileContent = "<xml><xmlnode></xmlnode></xml>"; // XML content.
string fileName = "MyFileName.xml";
If all you're looking to do is take XML you've already generated and add it to your existing request as content, you'll need to be able to write to the request stream. I don't particularly care for the stock model of getting the request stream, so I'd recommend the following extension to make your life a little easier:
public static class Extensions
{
public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.HttpWebRequest wr)
{
if (wr.ContentLength < 0)
{
throw new InvalidOperationException("The ContentLength property of the HttpWebRequest must first be set to the length of the content to be written to the stream.");
}
var tcs = new System.Threading.Tasks.TaskCompletionSource<System.IO.Stream>();
wr.BeginGetRequestStream((result) =>
{
var source = (System.Net.HttpWebRequest)result.AsyncState;
tcs.TrySetResult(source.EndGetRequestStream(result));
}, wr);
return tcs.Task;
}
}
From here, augment your SendRequest method:
public static void SendRequest(string myXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Might not hurt to specify encoding here
webRequest.ContentType = "text/xml; charset=utf-8";
// ContentLength must be set before a stream may be acquired
byte[] content = System.Text.Encoding.UTF8.GetBytes(myXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var response = await httpRequest(webRequest);
}
If the service you're trying to reach is a SOAP service, you could simplify this a bit more by having the IDE generate a client class for you. For more information on how to do that, check out this MSDN article. However, if the service does not have a Web Service Definition Language (WSDL) document, this approach will not be able to assist you.
You can use the HTTP Client libraries in Windows Phone 8 and use the client in the same way that Windows 8.
First, get the HTTP Client Libraries from Nuget.
And now, to perform a POST call
HttpClient client = new HttpClient();
HttpContent httpContent = new StringContent("my content: xml, json or whatever");
httpContent.Headers.Add("name", "value");
HttpResponseMessage response = await client.PostAsync("uri", httpContent);
if (response.IsSuccessStatusCode)
{
// DO SOMETHING
}
i hope this helps you :)
I have solved the problem in some other way..
class HTTPReqRes
{
private static HttpWebRequest webRequest;
public static void SendRequest()
{
webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("https://www.mydomain.com");
webRequest.Method = "PUT";
webRequest.ContentType = "text/xml; charset=utf-8";
webRequest.Headers["Header1"] = "Header1Value";
String myXml = "<Roottag><info>test</info></Roottag>";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(myXml);
webRequest.ContentLength = byteArray.Length;
// start the asynchronous operation
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
//webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
String myXml = <Roottag><info>test</info></Roottag>";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(myXml);
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
System.Diagnostics.Debug.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
}
This perfectly solves my problem, send an XML within the HTTP Request and in Response receive the XML from the web service.
I recommend using the RestSharp library. You can find a sample request here.
This is what I used. It's really simple, add WindowsPhonePostClient.dll to your References (if you can't, try unblock the file first by properties->unblock), then use this code:
private void Post(string YourUsername, string Password)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("User", YourUsername);
parameters.Add("Password", Password);
PostClient proxy = new PostClient(parameters);
proxy.DownloadStringCompleted += proxy_UploadDownloadStringCompleted;
proxy.DownloadStringAsync(new Uri("http://mytestserver.com/Test.php",UriKind.Absolute));
}
private void proxy_UploadDownloadStringCompleted(object sender,WindowsPhonePostClient.DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show(e.Result.ToString());
}
You need to create a reference to the webservice wsdl or you could try to do it manually as detailed here:
https://stackoverflow.com/a/1609427/2638872
//The below code worked for me. I receive xml response back.
private void SendDataUsingHttps()
{
WebRequest req = null;
WebResponse rsp = null;
string fileName = #"C:\Test\WPC\InvoiceXMLs\123File.xml"; string uri = "https://service.XYZ.com/service/transaction/cxml.asp";
try
{
if ((!string.IsNullOrEmpty(uri)) && (!string.IsNullOrEmpty(fileName)))
{
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
writer.WriteLine(ret);
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
HttpWebResponse hwrsp = (HttpWebResponse)rsp;
Stream streamResponse = hwrsp.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
rsp.Close();
}
}
catch (WebException webEx) { }
catch (Exception ex) { }
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}

How to make ordinary WebRequest async and awaitable?

I need to make the following code async and awaitable.
I need to get a lot of data from the web server, and then this data will be used to populate the xaml page in my application.
So, I need the DefLogin() method to be awaitable.
Is it possible?
public void DefLogin()
{
postData = "My Data To Post";
var url = new Uri("Url To Post to", UriKind.Absolute);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
Debug.WriteLine("Start BEGINGetResponse");
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
Debug.WriteLine("ERROR");
}
else
{
//Your response will be available in "Response"
Debug.WriteLine(Response);
}
}
catch (WebException)
{
//error
}
}
I saw this question on StackOverflow: Converting ordinary Http Post web request with Async and Await, but I could not understand the answer properly.
Please can anyone help? I would be really grateful!
You can use TaskFactory.FromAsync to convert APM to TAP, making a lot of tiny extension methods like this:
public static Task<Stream> GetRequestStreamAsync(this WebRequest request)
{
return TaskFactory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
}
and do the same for WebRequest.GetResponse and (if necessary) Stream.Write, Stream.Flush, etc.
Then you can write your actual logic using async and await without any callbacks:
public async Task DefLoginAsync()
{
postData = "My Data To Post";
var url = new Uri("Url To Post to", UriKind.Absolute);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
using (Stream postStream = await webRequest.GetRequestStreamAsync())
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
await postStream.WriteAsync(byteArray, 0, byteArray.Length);
await postStream.FlushAsync();
}
try
{
string Response;
using (var response = (HttpWebResponse)await webRequest.GetResponseAsync());
using (Stream streamResponse = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(streamResponse))
{
Response = await streamReader.ReadToEndAsync();
}
if (Response == "")
{
//show some error msg to the user
Debug.WriteLine("ERROR");
}
else
{
//Your response will be available in "Response"
Debug.WriteLine(Response);
}
}
catch (WebException)
{
//error
}
}

Properly closing Stream / StreamReader instance returned by function

I'm refactoring some code right now and found following function:
public static StreamReader DoWebRequest(string url, string method)
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = method;
req.Timeout = System.Threading.Timeout.Infinite;
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
return new StreamReader(resp.GetResponseStream());
}
and later
string result = Helper.DoWebRequest(ServerUrl, "GET").ReadToEnd();
I've used streams a lot and always put HttpWebResponse resp = req.GetResponse() and also stream readers into using block. But how should I do that in this particular case? Is the above code ok or it's better to assign the StreamReader to the new variable and explicitely close it after the call of ReadToEnd(); (or inside of using block) like this:
using(StreamReader sr = Helper.DoWebRequest(ServerUrl, "GET"))
{
string result = sr.ReadToEnd();
}
Thanks
Well, you can always write another function that does both:
public static String ReadToEndAndClose(this StreamReader stream)
{
using(var sr = stream)
{
return sr.ReadToEnd();
}
}

WP7 Create helper class for easy use HttpWebRequest with POST method

Actually I have something like this:
private void createHttpRequest()
{
System.Uri myUri = new System.Uri("..url..");
HttpWebRequest myHttpRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myHttpRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
string hash = HashHelper.createStringHash("123", "TEST", "0216");
// Create the post data
byte[] byteArray = createByteArrayFromHash(hash);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
ApiResponse apiResponse = (ApiResponse)JsonConvert.DeserializeObject<ApiResponse>(result);
}
}
It's good, it's working but now I must use these methods in every page and just change method createByteArrayFromHash which creates request. What if I want to create helper class that can help me to do this in something about 3 lines of code in page. How would you do that? I was thinking about this way but how to add request before response? Or would you do it another way? Thanks
Yeah, it's better to use async and await. Here is an example of such a wrapper:
public async Task<string> SendRequestGetResponse(string postData, CookieContainer cookiesContainer = null)
{
var postRequest = (HttpWebRequest)WebRequest.Create(Constants.WebServiceUrl);
postRequest.ContentType = "Your content-type";
postRequest.Method = "POST";
postRequest.CookieContainer = new CookieContainer();
postRequest.CookieContainer = App.Session.Cookies;
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes(postData);
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
// Can use cookies if you need
if (cookiesContainer == null)
{
if (!string.IsNullOrEmpty(postResponse.Headers["YourCookieHere"]))
{
var cookiesCollection = postResponse.Cookies;
// App.Session is a global object to store cookies and etc.
App.Session.Cookies.Add(new Uri(Constants.WebServiceUrl), cookiesCollection);
}
}
string response = await postStreamReader.ReadToEndAsync();
return response;
}
return null;
}
You can modify it as you wish

Categories