If I have this code in Windows Phone 8, for instance
string __retS = null;
private String postRequest(String url, String postData)
{
byte[]byteData = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = null;
try
{
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteData.Length;
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
} // end try
catch (Exception)
{
}
return __retS;
}
I put a breakpoint on this line request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);. I expected that execution will jump to my GetRequestStreamCallback method but it doesn't. It rather goes on to execute the return statement hence a null value is always returned.
Is that how its supposed to go?
Is that how its supposed to go?
Yes. When the work is done it will invoke the callback function you passed. See "Asynchronous Programming Model (APM)". Starting with .Net 4.5 / c# 5.0, you can use async/await which can help to write async codes simpler.
var stream = await request.GetRequestStreamAsync();
//...do some work using that stream
The callback is executed asynchronously, that means the code is continued after the asynchronous method is assigned. (request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);)
When the WebRequest is finished, the GetRequestStreamCallback is executed.
Because the UI thread would be blocked if this request was synchronous the windows phone sdk only serves an asynchronous one.
Related
public void SendPost(string code)
{
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
I want to call the GetRequestStreamCallback with an parameter.
Does anyone know how to do this?
Use a lambda instead of a method group.
That is:
webRequest.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, someParameter)), webRequest);
Instead of BeginGetRequestStream, use GetRequestStreamAsync. With it, you can use the async/await keywords to await for an operation to complete asynchronously and continue execution :
public async Task SendPost(string code)
{
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Start the request
var stream=await webRequest.GetRequestStream(webRequest);
MyStreamProcessingMethod(stream);
...
}
GetRequestStreamAsync and async/await are available in all supported .NET versions.
I have a problem with HttpWebRequest:
I have an ashx code in a visual studio ws that simply does:
public void ProcessRequest(HttpContext context)
{
var a = context.Request.Form["a"];
var b = context.Request.Form["b"];
context.Response.Write(a + " " + b);
}
I tried to call it with advancedRestClient and it worked, but if i call it with my windows phone device I get a not found exception and the request doesn't reach any breakpoint.
this is my WP code:
public void PostIt2()
{
string url = "http://localhost/blablacode/ecc.ashx";
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "{'a': 'avar','b':'bvar'}";
// 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
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();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
allDone.Set();
}
I took the code from MSDN so i don't know what i'm doing wrong, i also tried a lot of methods found on the internet, the only thing important for me is that i have to use HttpWebRequest and not HttpClient.
Can someone help me please?
Its possible that the problem is not in the code.
Are your services accesible from the phone??
Are your proyect configure with internet access??
If all its ok, look at this post:
httpclient postasync windows phone 8.1 universal app second call 404 error
Ok, really thanks god is friday.
i was using as url "localhost/eccecc.ashx"
device's localhost is not same localhost of computer.
I am trying send the http post from the windows phone to the server and I am getting some of problem via sending the post data.I put the break point in button_click_1 function and I found that it would not start the asynronous operation. Beside that, it also block the current thread and I know that this situation is cause by the allDone.waitOne().
Why the asynronous operation will not function and how to solve it?
Thank you for any help.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
allDone.WaitOne();
}
Asynronous operation:
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "xxxxxxxxxxx";
// 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
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private 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();
tbtesting.Text = responseString.ToString();
streamResponse.Close();
streamRead.Close();
response.Close();
allDone.Set();
}
You're not the first to hit this (see Is it possible to make synchronous network call on ui thread in wpf (windows phone)). If you do this then you deadlock the UI thread on Windows Phone.
The closest you're going to get is to use the async/await on your network calls. There are extension methods you can use to do this as part of the Microsoft.Bcl.Async package on NuGet.
I'm programming an application for Windows Phone 7. This application firstly sends, and then receives data from a server via HttpWebRequest. Most times it works fine, but sometimes, after receiving a portion of the data properly, I get a NullReferenceException in Stream.Read() function.
The communication starts when the user presses a button. Then I create the HttpWebRequest:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(sUri);
request.Method = "POST";
request.BeginGetRequestStream(GetRequestStreamCallback, request);
The request callback method:
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
postStream = request.EndGetRequestStream(asynchronousResult);
this.bSyncOK = Send(); //This is my method to send data to the server
postStream.Close();
if (this.bSyncOK)
request.BeginGetResponse(GetResponseCallback, request);
else
manualEventWait.Set(); //This ManualResetEvent notify a thread the end of the communication, then a progressbar must be hidden
}
The response callback method:
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult) )
{
using (streamResponse = new StreamReader(response.GetResponseStream() ) )
{
this.bSyncOK = Recv(); //This is my generic method to receive the data
streamResponse.Close();
}
response.Close();
}
manualEventWait.Set(); //This ManualResetEvent notify a thread the end of the communication, then a progressbar must be hidden
}
And finally, this is the code where I get the exception reading the stream data:
int iBytesLeidos;
byte[] byteArrayUTF8 = new byte[8];
iBytesLeidos = streamResponse.BaseStream.Read(byteArrayUTF8, 0, 8); //NullReferenceException!!! -Server always send 8 bytes here-
When the application starts, I create a background thread that frequently sends info to the server. Background and Manual communications can run simultaneously. Could this be a problem?
Thanks.
If streamResponse is global variable, it can cause the problem in a case of an access from another thread. Pass your Stream to the Recv as a parameter
using (StreamReader streamResponse = new StreamReader(response.GetResponseStream() ) )
{
this.bSyncOK = Recv(streamResponse); //This is my generic method to receive the data
streamResponse.Close();
}
Where is your streamResponse declared in latter snippet? Is it the same object as in 3d snippet? Maybe you just use another variable, instead of actual stream.
in the second snippet, try to delete "postStream.Close();".
I have a class that goes and grabs some data and returns it as a string. While this object is working there is a spinning icon letting the user know work is being done. The problem is the code exits before the response comes back. I stuck a
while(response == null)
In just to see whats going on and the
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
is not firing. It fires ok in a console application so I am putting this down to something I am doing that silverlight doesn't like, heres the full code:
public class HttpWorker
{
private HttpWebRequest request;
private HttpWebResponse response;
private string responseAsString;
private string url;
public HttpWorker()
{
}
public string ReadFromUrl(string Url)
{
url = Url;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
AsyncRequest(); // The Demon!
return responseAsString;
}
private void AsyncRequest()
{
request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), null);
}
private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
{
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
if (response.StatusCode == HttpStatusCode.OK)
{
// Create the stream, encoder and reader.
Stream responseStream = response.GetResponseStream();
Encoding streamEncoder = Encoding.UTF8;
StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
responseAsString = responseReader.ReadToEnd();
}
else
{
throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
}
}
}
Are you going into the busy loop with (while response == null) on the UI thread? The async callback for the HttpRequest will be delivered on the UI thread, so if you're looping on that same thread, the callback can never run. You need to return to allow the main message loop to run, and then your async callback will be delivered.
Your design above suggests that what you really want is a synchronous fetch anyway. Forget the callback and just call FinaliseAsyncRequest inside ReadFromUrl yourself. The UI will hang until the request completes, but it sounds like that's what you want.
I posted a working sample here of using WebClient and HttpWebRequest.
WebClient, HttpWebRequest and the UI Thread on Windows Phone 7
Note the latter is preferred for any non trivial processing to avoid blocking the UI.
Feel free to reuse the code.
The easiest way to get a string from a web server is to use WebClient.DownloadStringAsync() (MSDN docs).
Try something like this:
private void DownloadString(string address)
{
WebClient client = new WebClient();
Uri uri = new Uri(address);
client.DownloadStringCompleted += DownloadStringCallback;
client.DownloadStringAsync(uri);
StartWaitAnimation();
}
private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
{
// Do something with e.Result (which is the returned string)
StopWaitAnimation();
}
Note that the callback executes on the UI thread and so you should only use this method if your callback method is not doing very much as it will block the UI while it executes.
If you need more control over the web request then you can use HttpWebRequest.
If you really must imitate synchronous behaviour have a look at Faking synchronous calls in Silverlight WP7