使用HttpWebRequest进行异步的POST操作

会在EndGetResponse的地方提示ArgumentException###

img

09-18
使用MSDN上BeginGetRequestStream的示例,会出现一样的信息。这块应该没问题。继续检查

09-18
其实是RequestStream写入失败。stream和RequestStream的关联方式肯定有问题。

应该是由于异步操作,在没有Begin的情况下执行End操作。
两处EndGetResponse都会出现。可以先用try-catch忽略,正在解决

回到旧的地方。继续想办法解决EndGetRequestStream和EndGetResponse的问题上。

09-25
借鉴微软官方示例:
HttpClient里的PostText部分
具体用法

try
{
    HttpResponseMessage response = await httpClient.PostAsync(new Uri(POSTurl),
         new HttpStringContent(POSTdata)).AsTask(cts.Token);

    testBox.Text = string.Empty;
    await Helpers.DisplayTextResultAsync(response, testBox, cts.Token);
}
catch (TaskCanceledException)
{
    string str = "cancled";
}
catch (Exception ex)
{
    string str = ex.ToString();
}
finally
{
    string str = "finished";
}

获得Json数据后,需要转换成对应的变量,原计划也使用微软官方提供的方法查看详情,但是不适用。继续使用旧的方法:

 try
{
    System.Runtime.Serialization.Json.DataContractJsonSerializer a = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(NewsList));
    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(test)))
    {
        NewsList newsTest= (NewsList)a.ReadObject(stream);

    }
}
catch (Exception e)
{

    string str = e.ToString();
}
原文地址:https://www.cnblogs.com/woodytian/p/4818580.html