C# read from HttpResponseMessage - c#

I am using .net's Httpclient for the first time and finding it very hard. I have managed to call the server and receive response from it but stuck at reading from the response. Here is my code:
if (Method == HttpVerb.POST)
response = client.PostAsync(domain, new StringContent(parameters)).Result;
else
response = client.GetAsync(domain).Result;
if (response != null)
{
var responseValue = string.Empty;
Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
{
var stream = t.Result;
using (var reader = new StreamReader(stream))
{
responseValue = reader.ReadToEnd();
}
});
return responseValue;
}
responseValue has {} in it although the service is returning data. How should I fix the issue?
The project is in .Net 4.

You are creating an asynchronous task but not waiting for it to complete before returning. This means your responseValue never gets set.
To fix this, before your return do this:
task.Wait();
So your function now looks like this:
if (Method == HttpVerb.POST)
response = client.PostAsync(domain, new StringContent(parameters)).Result;
else
response = client.GetAsync(domain).Result;
if (response != null)
{
var responseValue = string.Empty;
Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
{
var stream = t.Result;
using (var reader = new StreamReader(stream))
{
responseValue = reader.ReadToEnd();
}
});
task.Wait();
return responseValue;
}
If you prefer to use await (which you possibly should), then you need to make the function this code is contained in async. So this:
public string GetStuffFromSomewhere()
{
//Code above goes here
task.Wait();
}
Becomes:
public async string GetStuffFromSomewhere()
{
//Code above goes here
await ...
}

Try this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(obj.Url);
HttpWebResponse response = null;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (Exception ex)
{
}

Related

C# Xamarin Android Rest call in PCL error "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."

I have used SO to help with several issues in the past. However, I cannot find a solution to something I have been struggling with for 2 days now.
I am a noob, please be kind :)
I have an app that I created using Xamarin Studio, targeted for Android. It is a basic GET request from a Rest Api. It was working perfectly until I realized I was not helping myself when it came time to create the same app in IOS and Windows. Once I changed my project to utilize a PCL I started getting errors, primarily around my RestClient class (originally got from http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp)
From my droid app class:
var apiUser = GetString(Resource.String.apiUser);
var apiPass = GetString(Resource.String.apiPass);
//Get token from API
string token = authenticate(apiUser,apiPass);
public static string authenticate(string apiUser, string apiPass)
{
Authentication Auth = new Authentication ();
try
{
// set json by passing AuthenticationUrl as endpoint, returns json data
var o = JObject.Parse(EntryRepository.getJson(PJTApiUrls.getAuthenticationUrl(apiUser,apiPass)));
Auth.Token = (string)o["Token"];
return Auth.Token;
}
catch (Exception e)
{
// Couldn't do stuff. Log the exception.
// TODO possible timeout, try again, if fails again then return error message
if (e.Message.Contains("400") || e.Message.Contains("401"))
{
string error = string.Format("Invalid credentials, please try again");
return error;
} else {
string error = string.Format ("An error occurred: \r\n{0}", e.Message);
return error;
}
}
}
getAuthenticationUrl gets the api URL.
Here is getJson (in PCL):
public static string getJson(string endpoint)
{
string apiurl = endpoint;
var client = new _RestClient();
client.EndPoint = apiurl;
client.ContentType = "application/json";
client.Method = HttpVerb.GET;
//client.Method = HttpVerb.POST;
client.PostData = "";
//client.PostData = "{postData: value}";
//client.PostData = "{'someValueToPost': 'The Value being Posted'}";
var json = client._MakeRequestAsync();
// to append parameters, pass them into make request:
//var json = client.MakeRequest("?param=0");
return json.ToString();
}
And for the _RestClient class (in PCL):
public async Task<string> _MakeRequestAsync()
{
try {
var request = _MakeRequestAsync ("");
return await request;
}
catch (Exception e){
return e.Message;
}
}
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
var request = WebRequest.Create(uri) as HttpWebRequest;
using (var response = await request.GetResponseAsync () as HttpWebResponse) {
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) {
var message = String.Format ("Request failed. Received HTTP {0}", response.StatusCode);
throw new Exception (message);
}
// grab the response
using (var responseStream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)) {
//using (var responseStream = response.GetResponseStream ()) {
if (responseStream != null)
using (var reader = new StreamReader (responseStream)) {
responseValue = reader.ReadToEnd ();
}
}
return responseValue;
}
}
responseValue is returning null
return await request is saying "Status = Waiting for activation"
I have also had the error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
But this works if the RestClient class is within Droid (Instead of the shared PCL) and contains the following:
public string MakeRequest ()
{
return MakeRequest ("");
}
public string MakeRequest (string parameters)
{
var request = (HttpWebRequest)WebRequest.Create (EndPoint + parameters);
request.Method = Method.ToString ();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty (PostData) && Method == HttpVerb.POST) {
var bytes = Encoding.GetEncoding ("iso-8859-1").GetBytes (PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream ()) {
writeStream.Write (bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse ()) {
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) {
var message = String.Format ("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException (message);
}
// grab the response
using (var responseStream = response.GetResponseStream ()) {
if (responseStream != null)
using (var reader = new StreamReader (responseStream)) {
responseValue = reader.ReadToEnd ();
}
}
return responseValue;
}
}
I cannot figure this out, any help/guidance is appreciated. Let me know if I can clarify anything.
***** UPDATE ***** Thanks to #milen-pavlov help thus far, here is where I am currently at:
in Android project:
var apiUser = GetString(Resource.String.apiUser);
var apiPass = GetString(Resource.String.apiPass);
//Get token from API
var token = await authenticate(apiUser,apiPass);
lblOutput.Text = token;
calls (also in Android project):
public static async Task<string> authenticate(string apiUser, string apiPass)
{
Authentication Auth = new Authentication ();
try
{
// set json by passing AuthenticationUrl as endpoint, returns json data
var o = JObject.Parse(await EntryRepository.getJson(PJTApiUrls.getAuthenticationUrl(apiUser,apiPass)));
Auth.Token = (string)o["Token"];
return Auth.Token;
}
catch (Exception e)
{
if (e.Message.Contains("400") || e.Message.Contains("401"))
{
string error = string.Format("Invalid credentials, please try again");
return error;
} else {
string error = string.Format ("An error occurred: \r\n{0}", e.Message);
return error;
}
}
}
Calls json class in PCL project:
public static async Task<string> getJson(string endpoint)
{
string apiurl = endpoint;
var client = new _RestClient();
client.EndPoint = apiurl;
client.ContentType = "application/json";
client.Method = HttpVerb.GET;
client.PostData = "";
var json = await client._MakeRequestAsync();
return json;
}
which then calls restclient class in PCL project:
public async Task<string> _MakeRequestAsync()
{
var request = _MakeRequestAsync ("");
return await request;
}
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
return await response.Content.ReadAsAsync<string>();
};
}
End result/error:
Any guidance is appreciated!
Can you use HttpClient instead?
Sample Get request will look similar to this:
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
return await result.Content.ReadAsStringAsync();
};
}

Call UI thread in HttpWebRequest.BeginGetResponse

Good night, I'm trying to call the UI thread, to update a proprety actualy, inside HttpWebRequest.BeginGetResponse method by using CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync method. But it does not work, I do not know how it works actually. There is my code:
private void DebutReponse(IAsyncResult resultatAsynchrone)
{
HttpWebRequest requete = (HttpWebRequest)resultatAsynchrone.AsyncState;
Stream postStream = requete.EndGetRequestStream(resultatAsynchrone);
string donneesAEnvoyer = "username=" + Name + "&password=" + Password + "&email=" + Email;
string lol = donneesAEnvoyer;
byte[] tableau = Encoding.UTF8.GetBytes(donneesAEnvoyer);
postStream.Write(tableau, 0, donneesAEnvoyer.Length);
postStream.Close();
requete.BeginGetResponse(FinReponse, requete);
}
private void FinReponse(IAsyncResult resultatAsynchrone)
{
HttpWebResponse aResp = null;
try
{
HttpWebRequest requete = (HttpWebRequest)resultatAsynchrone.AsyncState;
WebResponse webResponse = requete.EndGetResponse(resultatAsynchrone);
Stream stream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string reponse = streamReader.ReadToEnd();
stream.Close();
streamReader.Close();
webResponse.Close();
//ErrorGridHeight = new GridLength(0.3, GridUnitType.Star);
ErrorMsg = msgSucceed;
}
catch (WebException e)
{
if (e.Response != null)
{
aResp = e.Response as HttpWebResponse;
}
}
if (aResp != null)
await errorFunc();
}
private async Task errorFunc()
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ErrorMsg = msgFailed);
}
I have an error telling me that I can only use the await operator inside an async method who return a Task. I have no idea how it works.
EDIT:
Ok so I changed my code a little bit to avoid the problem of this function:
requete.BeginGetResponse(FinReponse, requete);
because she want a function with a specific prototype so I did this:
private async Task lol(IAsyncResult resultatAsynchrone)
{
HttpWebResponse aResp = null;
try
{
HttpWebRequest requete = (HttpWebRequest)resultatAsynchrone.AsyncState;
WebResponse webResponse = requete.EndGetResponse(resultatAsynchrone);
Stream stream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string reponse = streamReader.ReadToEnd();
stream.Close();
streamReader.Close();
webResponse.Close();
//ErrorGridHeight = new GridLength(0.3, GridUnitType.Star);
ErrorMsg = msgSucceed;
}
catch (WebException e)
{
if (e.Response != null)
{
aResp = e.Response as HttpWebResponse;
}
}
if (aResp != null)
await errorFunc();
}
private void FinReponse(IAsyncResult resultatAsynchrone)
{
Task.Run(() => lol(resultatAsynchrone));
}
private async Task errorFunc()
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ErrorMsg = msgFailed);
}
The only problem is that it does not change the proprety, it does not go into the set of my proprety. And I have an exeption which is:
System.NotImplementedExeption
Thank you for the help.
Try to change your errorFunc() to this.
private void errorFunc()
{
CoreApplication.MainView.CoreWindow.Dispatcher.BeginInvoke(() =>
{
ErrorMsg = msgFailed;
});
}
I also found another place, where you're trying to change ErrorMsg witouth calling the UI thread. It's the line with code ErrorMsg = msgSucceed;. I suggest to use the same way, so replace the line with this:
CoreApplication.MainView.CoreWindow.Dispatcher.BeginInvoke(() =>
{
ErrorMsg = msgSucceed;
});
You have to do FinReponse method async to be able to use await operator into it:
private async void FinReponse(IAsyncResult resultatAsynchrone)
So I found the answer to access the UI, I have to use:
Deployment.Current.Dispatcher.BeginInvoke(()=>mym());
and it works perfectly.
Thanks for everythings.

GetData from server Windows 8

I have next function:
private void getAllData()
{
HttpWebRequest request = HttpWebRequest.CreateHttp("http://webservice.com/wfwe");
request.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), request);
}
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();
GetApplications(result);
}
}
And i fill in stack panels:
private void GetApplications(string result)
{
var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(result);
foreach (Applications A in ApplicationsList)
{
foreach (ApplicationRelation SCA in A.ApplicationRelations)
{
if (SCA.ApplicationSubcategory != null)
{
#region Fill Customer Research Stack
if (SCA.ApplicationSubcategory.subcategoryName == "Customer Research")
{
if (TestStack.Children.Count == 0)
{
ApplicationTile AT = FillDataForApplicationTile(SCA);
AT.Margin = new Thickness(5, 0, 5, 0);
TestStack.Children.Add(AT);
}
}
#endregion
}
}
}
}
And code fails at:
if (TestStack.Children.Count == 0)
Error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
How can i rewrite my Request from void to string, so i could do something like this:
GetApplications(await getAllData())
EDIT 2 for dcastro:
EDIT 3:
Thanks it works, but i was looking for something like this:
//Modified your code:
GetApplications(getAllData2().Result);
private async Task<string> getAllData2()
{
string uri = "http://webservice.com/wfe";
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
return result.ToString();
}
But somehow my construction doesn't enter GetApplication function...
Instead of using AsyncCallback (which I'm pretty sure is running GetResponsetStreamCallback in a non-UI thread), try fetching your data like this:
private async void getAllData()
string uri = "http://webservice.com/wfwe";
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
string body = await response.Content.ReadAsStringAsync();
GetApplications(body);
}
This will call your webservice asynchronously (at line await Client.sendMessageAsync(msg);), and return to the original UI thread when the response is received. This way, you can update UI elements, like your TestStack.
Edit fixed bug
Try this.
private async Task<string> getAllData()
{
string Result = "";
var http = new HttpClient();
var response = await http.GetAsync("http://webservice.com/wfwe"); // I am considering this URL gives me JSON
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Result = await response.Content.ReadAsStringAsync(); // You will get JSON here
}
else
{
Result = response.StatusCode.ToString(); // Error while accesing the web service.
}
return Result;
}
private async Task GetApplications(string result)
{
var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(result);
foreach (Applications A in ApplicationsList)
{
foreach (ApplicationRelation SCA in A.ApplicationRelations)
{
if (SCA.ApplicationSubcategory != null)
{
#region Fill Customer Research Stack
if (SCA.ApplicationSubcategory.subcategoryName == "Customer Research")
{
if (TestStack.Children.Count == 0)
{
// This will update your UI using UI thread
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
ApplicationTile AT = FillDataForApplicationTile(SCA);
AT.Margin = new Thickness(5, 0, 5, 0);
TestStack.Children.Add(AT);
});
}
}
#endregion
}
}
}
}

Asynchronously using HttpWebRequest without blocking UI thread

I am trying to use HttpWebRequest and HttpWebResonse asynchronously in a WinForms application without blocking my UI thread.
I saw this similar SO Question which explains how to do it. However, I am not 100% sure the accepted answer is the correct way to do it. The accepted answer is using BeginGetResponse.
According to the MSDN documentation:
The BeginGetResponse method requires some synchronous setup tasks to
complete (DNS resolution, proxy detection, and TCP socket connection,
for example) before this method becomes asynchronous. As a result,
this method should never be called on a user interface (UI) thread
because it might take some time, typically several seconds.
Can someone please provide me with the correct way to do this. Here is my C# function that I'm trying to make work "properly" without blocking my UI thread:
private IDictionary<string, object> CreateWebRequest(string endPoint, string method, string data, bool addAuthHeader)
{
var req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Method = method;
if (addAuthHeader)
{
req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}
if (!string.IsNullOrEmpty(data))
{
var utfenc = new UTF8Encoding();
byte[] buffer = utfenc.GetBytes(data);
req.ContentLength = buffer.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (Stream strm = req.GetRequestStream())
{
strm.Write(buffer, 0, buffer.Length);
strm.Close();
}
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
if (_accessToken == null)
{
throw;
}
var responseError = (HttpWebResponse)e.Response;
if (responseError.StatusCode == HttpStatusCode.Unauthorized)
{
var stackTrace = new StackTrace();
var q = stackTrace.GetFrame(1).GetMethod().Name;
RefreshAccessCode();
req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Method = method;
if (addAuthHeader)
{
req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}
response = (HttpWebResponse)req.GetResponse();
}
}
string jsonResponse = null;
if (response != null)
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
jsonResponse = reader.ReadToEnd();
}
}
}
return DeserializeResponse(jsonResponse);
}
If you're open to something besides WebRequest, I'm a fan of System.Net.WebClient. It uses System.Threading.Tasks instead of BeginGetResponse() and EndGetResonse().
public async Task<Dictionary<string, object>> CreateWebRequest(string endPoint, string method, string data, bool addAuthHeader)
{
WebClient client = new WebClient();
if (addAuthHeader)
{
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}
byte[] buffer = null;
if (!string.IsNullOrEmpty(data))
{
var utfenc = new UTF8Encoding();
buffer = utfenc.GetBytes(data);
}
else
{
buffer = new byte[0];
}
return await client.UploadDataTaskAsync(endPoint, method, buffer)
.ContinueWith((bytes) =>
{
string jsonResponse = null;
using (var reader = new StreamReader(new MemoryStream(bytes)))
{
jsonResponse = reader.ReadToEnd();
}
return DeserializeResponse(jsonResponse);
});
}
}
To use your existing code, just add a method that is intended to execute on the UI thread, and create your web request on a separate thread. When the web request is complete you call the final method on the UI thread. So, a simple version would be:
//do some stuff that wont block the ui thread here
ThreadPool.QueueUserWorkItem((o) =>
{
IDictionary<string, object> result =
CreateWebRequest("lalala", "lol", "butts", true);
BeginInvoke(OnAsyncWebRequestComplete, result);
}, null);
private void OnAsyncWebRequestComplete(IDictionary<string, object> result)
{
//do some stuff on the UI thread here
}

Converting ordinary Http Post web request with Async and Await

How I can convert my traditional HttpWebRequest "POST" call with Async / Await pattern, Here with this I am attaching my current code, Any one please help me to convert this code using Async / Await pattern for windows phone 8.
public void GetEnvironmentVariables(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback)
{
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject
{
new JProperty("apiKey",_api),
new JProperty("affiliateId",_affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
byte[] requestBody = Encoding.UTF8.GetBytes(serializedResult);
request.BeginGetRequestStream(GetRequestStreamCallback, new object[] { request, requestBody });
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)((object[])asynchronousResult.AsyncState)[0];
using (var postStream = request.EndGetRequestStream(asynchronousResult))
{
var byteArray = (byte[])((object[])asynchronousResult.AsyncState)[1];
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
}
request.BeginGetResponse(GetResponseCallback, request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err))
CredentialsCallback(Credentails);
else
{
if (Credentails != null)
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
string responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
ErrorCallback(we);
}
}
Since Windows Phone 8 doesn't seem to offer the TAP methods you need such as GetRequestStreamAsync the first thing to do is write a little wrapper to provide them for yourself:
public static class WebRequestAsyncExtensions
{
public static Task<Stream> GetRequestStreamAsync(this WebRequest request)
{
return Task.Factory.FromAsync<Stream>(
request.BeginGetRequestStream, request.EndGetRequestStream, null);
}
public static Task<WebResponse> GetResponseAsync(this WebRequest request)
{
return Task.Factory.FromAsync<WebResponse>(
request.BeginGetResponse, request.EndGetResponse, null);
}
}
Note the use of Task.Factory.FromAsync - this is the preferred way to get an await-friendly wrapper around an APM-based async API such as those offered by WebRequest. This is far more efficient than using Task.Factory.StartNew as suggested by someone else, because that would spin up a new thread, whereas this won't need to.
With this in place, you can now write your code in the same way you would on platforms where these TAP-style methods are available (e.g. Windows 8 store apps, desktop apps, etc.):
public async Task GetEnvironmentVariablesAsync(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback)
{
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject
{
new JProperty("apiKey",_api),
new JProperty("affiliateId",_affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
byte[] requestBody = Encoding.UTF8.GetBytes(serializedResult);
// ASYNC: using awaitable wrapper to get request stream
using (var postStream = await request.GetRequestStreamAsync())
{
// Write to the request stream.
// ASYNC: writing to the POST stream can be slow
await postStream.WriteAsync(requestBody, 0, requestBody.Length);
}
try
{
// ASYNC: using awaitable wrapper to get response
var response = (HttpWebResponse) await request.GetResponseAsync();
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
// ASYNC: using StreamReader's async method to read to end, in case
// the stream i slarge.
string responseString = await reader.ReadToEndAsync();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err))
CredentialsCallback(Credentails);
else
{
if (Credentails != null)
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
string responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
ErrorCallback(we);
}
}
Note the four lines with // ASYNC: comments - these show where I've made changes. I've collapsed your method down to one, because that's a) possible once you're using async and await and b) much easier than trying to pass things from one method to the next using state arguments.
Notice that the second and fourth of these actually makes async some things you were previously doing synchronously: writing data into the request stream, and reading data out of the response stream. For a small request this probably doesn't matter, but if large amounts of data are being transferred, a synchronous call to Write or ReadToEnd may block. Fortunately, although Windows Phone 8 appears to be missing the TAP methods on WebRequest, it does offer them on Stream and StreamReader so this works without needing to write any extension methods.
I'm new to the community, so here goes my first post. In this case, you can return anytype using a generic Task. This has worked well for me in the past.
Server Side
public class MyController : ApiController
{
public Task<string> PostAsync()
{
return Task.Factory.StartNew(() =>
{
return "populate me with any type and data, but change the type in the response signature.";
});
}
}
Client Side
public class HomeController : Controller
{
public Task<ViewResult> Index()
{
return Task.Factory.StartNew(() =>
{
var model = "use a provider, get some data, or something";
return View(model);
});
}
}
This should do the job:
public async void GetEnvironmentVariables(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback) {
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject {
new JProperty("apiKey", _api),
new JProperty("affiliateId", _affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
var requestBody = Encoding.UTF8.GetBytes(serializedResult);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBody, 0, requestBody.Length);
await GetResponse(request);
}
private async Task GetResponse(WebRequest request) {
Stream resStream = null;
try {
var response = await request.GetResponseAsync();
if (response == null) {
return;
}
resStream = response.GetResponseStream();
if (resStream == null) {
return;
}
var reader = new StreamReader(resStream);
var responseString = await reader.ReadToEndAsync();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err)) {
CredentialsCallback(Credentails);
}
else {
if (Credentails != null) {
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we) {
if (resStream != null) {
var reader = new StreamReader(resStream);
var responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
}
ErrorCallback(we);
}
}

Categories

Resources