HttpWebRequest BeginGetRequestStream callback neve

2019-08-10 12:42发布

问题:

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

回答1:

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;
}


回答2:

Finally solved this by switching to Profile 78 and HttpClient, which works well in all cases.