HttpWebRequest BeginGetRequestStream callback never called

独自空忆成欢 提交于 2019-12-11 08:52:10

问题


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.



来源:https://stackoverflow.com/questions/22572084/httpwebrequest-begingetrequeststream-callback-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!