GetResponse没有使用HttpWebRequest回来

时间:2019-06-17 20:05:08

标签: c# asp.net .net

使用表单内容类型,我陷入了这一行:

var webresponse = (HttpWebResponse)webrequest.GetResponse();

对于url,您可以使用任何值。这是完整的代码:

public bool test() 
{

    string url = "https://www.google.com";

    // Create a new HTTP request object, set the method to POST and write the POST data to it
    var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
    webrequest.Method = "POST";
    webrequest.ContentType = "application/x-www-form-urlencoded";

    using (Stream postStream = webrequest.GetRequestStream())
    {
        //
    }

    // Make the request, get a response and pull the data out of the response stream
    var webresponse = (HttpWebResponse)webrequest.GetResponse();
    Stream responseStream = webresponse.GetResponseStream();
    var reader = new StreamReader(responseStream);

    string result = reader.ReadToEnd();

    // Normal Completion
    return true;
}

有人知道为什么它会卡在这条线上而又不回来(在进行调试时):

var webresponse = (HttpWebResponse)webrequest.GetResponse();

谢谢

1 个答案:

答案 0 :(得分:1)

我发现了问题!我将方法称为异步任务:

private async Task starttest()
{
    clsTester objTester = new clsTester();
    objTester.test();
}

...

var result = Task.Run(async () => await starttest());

我删除了所有代码并将其更改为工作线程:

private Thread workerThread = null;
private void starttest()
{
    clsTester objTester = new clsTester();
    objTester.test();
}

然后将其命名如下:

...

// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.starttest));
this.workerThread.Start();

现在一切正常。