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();".
Related
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 recently wrote an async HttpWebRequest client for our application and it works fine in .NET 3.5, but on Mono it fails to correctly write the data on to the request before sending it out.
I have confirmed the problem using wireshark to sniff the outgoing packets. The HTTP request is correctly set to POST with a JSON Content Type however the Content-Length and data are 0.
I currently get one exception:
The number of bytes to be written is greater than the specified
ContentLength.
I have tried to resolve this by manually setting the ContentLength of the WebRequest and changing the way I encode the data before giving it to the stream (I have tried both a Steam and StreamWriter).
I have also stepped through the code and debug logged the variables in the async method to ensure the data is really there. It just does not appear to be getting to the WebRequest object.
Here is the relevant code:
private void StartWebRequest(string payload) {
var httpWebRequest = (HttpWebRequest)WebRequest.Create(PortMapSleuthURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null; // Setting this to null will save some time.
// start an asynchronous request:
httpWebRequest.BeginGetRequestStream(GetRequestStreamCallback, new object[] {httpWebRequest, payload});
try {
// Send the request and response callback:
httpWebRequest.BeginGetResponse(FinishPortTestWebRequest, httpWebRequest);
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
private void GetRequestStreamCallback(IAsyncResult asyncResult) {
try {
object[] args = (object[])asyncResult.AsyncState;
string payload = (string)args[1];
HttpWebRequest request = (HttpWebRequest)args[0];
//StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), new UTF8Encoding(false));
StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), Encoding.UTF8);
// Write to the request stream.
streamWriter.Write(payload);
streamWriter.Flush();
streamWriter.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
I don't think you are supposed to call BeginGetResponse before EndGetRequestStream. That is, I would move that into the GetRequestStreamCallback. This is how the example on msdn works too.
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.
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 trying to stream radio in a Windows Phone 7 app and for this I'm using ManagedMediaHelpers. The HttpWebRequest to get the continuous stream works but doesn't call the callback Url because of the continuous stream.
How do I access the stream without the help of the callback Url? On other posts some said O need to use reflection but does someone knows hot to implement it? Here is my code:
req = (HttpWebRequest) WebRequest.Create(
"http://streamer-dtc-aa01.somafm.com:80/stream/1018");
// if this is false it will fire up the callback Url
// but the mediastreamsource will throw an exception
// saying the it needs to be true
req.AllowReadStreamBuffering = true;
IAsyncResult result = req.BeginGetResponse(RequestComplete,null);
private void RequestComplete(IAsyncResult r)
{
HttpWebResponse resp = req.EndGetResponse(r) as HttpWebResponse;
Stream str = resp.GetResponseStream();
mss = new Mp3MediaStreamSource(str, resp.ContentLength);
Deployment.Current.Dispatcher.BeginInvoke(() => {
this.me.Volume = 100;
this.me.SetSource(mss);
});
}
Had the same issue, so here is how I solved it:
Getting bytes from continuous streams on Windows Phone 7
It might also be a problem with your URL - make sure that if you run the request outside the application, you are getting the necessary amount of data.