HttpWebRequest从不调用BeginGetRequestStream回调

时间:2014-03-22 01:03:10

标签: c# post httpwebrequest xamarin mvvmcross

在我的Xamarin应用程序中,我使用HttpWebRequest类将POST消息发送到服务器(我使用它,因为它在PCL库中是开箱即用的)。

以下是一些请求准备代码:

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

当我开始应用并第一次和第二次执行此代码时,一切正常。但是当第3次(确切地说!)执行时,不会调用回调并且行" BeginGetRequestStream回调"永远不会打印到日志。它是类实现中的错误还是我做错了什么?

如果无法在Xamarin中使用,请建议可靠方便的类,以便在超时时发送Http GET和POST请求。

还创建了相关的,更一般的问题:Sending Http requests from Xamarin Portable Class Library

2 个答案:

答案 0 :(得分:2)

我在Xamarin PCL中发送和接收消息JSON的解决方案:

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

答案 1 :(得分:-1)

最后通过切换到Profile 78和HttpClient来解决这个问题,它在所有情况下都能正常运行。