简体   繁体   中英

HttpWebRequest BeginGetRequestStream callback never called

In my Xamarin application I use HttpWebRequest class to send POST messages to the server (I use it because it is available out-of-the box in PCL libraries).

Here is some request preparation code:

    request.BeginGetRequestStream (asyncResult => {
        Mvx.Trace ("BeginGetRequestStream callback");

        request = (HttpWebRequest)asyncResult.AsyncState;
        Stream postStream = request.EndGetRequestStream (asyncResult);

        string postData = jsonConverter.SerializeObject (objectToSend);

        Mvx.Trace ("Posting following JSON: {0}", postData);

        byte[] byteArray = Encoding.UTF8.GetBytes (postData);

        postStream.Write (byteArray, 0, byteArray.Length);

        MakeRequest (request, timeoutMilliseconds, successAction, errorAction);
    }, request);

When I start application and execute this code for the first and the second time everything works fine. But when this is executed for the 3rd time (exactly!) the callback is not called and line "BeginGetRequestStream callback" is never printed to log. Is it a bug in class implementation or maybe I do something incorrectly?

If it is not possible to make this working in Xamarin please suggest reliable and convenient class for sending Http GET and POST request with timeout.

Also created related, more general question: Sending Http requests from Xamarin Portable Class Library

My solution to send and receive messages JSON in Xamarin PCL:

public async Task<string> SendMessageJSON(string message, string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.ContentType = "application/json";
    request.Method = "POST";

    // Send data to server
    IAsyncResult resultRequest = request.BeginGetRequestStream(null, null);
    resultRequest.AsyncWaitHandle.WaitOne(30000); // 30 seconds for timeout

    Stream streamInput = request.EndGetRequestStream(resultRequest);
    byte[] byteArray = Encoding.UTF8.GetBytes(message);

    await streamInput.WriteAsync(byteArray, 0, byteArray.Length);
    await streamInput.FlushAsync();

    // Receive data from server
    IAsyncResult resultResponse = request.BeginGetResponse(null, null);
    resultResponse.AsyncWaitHandle.WaitOne(30000); // 30 seconds for timeout

    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(resultResponse);
    Stream streamResponse = response.GetResponseStream();
    StreamReader streamRead = new StreamReader(streamResponse);
    string result = await streamRead.ReadToEndAsync();
    await streamResponse.FlushAsync();

    return result;
}

最终通过切换到Profile 78和HttpClient来解决此问题,该方法在所有情况下均适用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM