冻结并挂起我的程序

冻结并挂起我的程序

本文介绍了C#httpwebrequest getResponse()冻结并挂起我的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用httpwebrequest在远程服务器上使用诸如服务之类的其他服务,并且从第一次执行本身开始,我的代码就挂了程序.然后我尝试将其作为控制台应用程序,以确保它与程序本身无关,但没有运气!

I was trying to use httpwebrequest to use a rest like service on a remote server and from the first execution itself, my code was hanging the program. Then I tried it as a console application to make sure it has nothing to do with the program itself but no luck!

        string credentialsJson = @"{""username"":""test"",
                                      ""password"":""test""
                                   }";

        int tmp = ServicePointManager.DefaultConnectionLimit;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://qrua.com/qr/service" + @"/auth/login");
        request.Method = "POST";
        request.KeepAlive = true;
        request.Timeout = 50000 ;
        request.CookieContainer = new CookieContainer();
        request.ContentType = "application/json";
        try
        {
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(credentialsJson);
        }
        catch (Exception e)
        {
            Console.WriteLine("EXCEPTION:" + e.Message);
        }

        //WebResponse response = request.GetResponse();
        try
        {
            using (WebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Console.WriteLine("request:\n" + request.ToString() + "\nresponse:\n" + response.ContentLength);
                response.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("EXCEPTION: in sending http request:" + " \nError message:" + e.Message);
        }

尝试了来自不同论坛的几件事,但没有帮助.即使是带有上述代码的简单控制台应用程序,也会无限期地挂起控制台!任何帮助都会很棒..

Tried several things from different forums but it doesnt help. Even a simple console app with the above code hangs the console indefinitely! Any help would be great..

谢谢

推荐答案

您永远不会关闭StreamWriter ...,所以我怀疑它没有被刷新.诚然,我希望服务器会出现错误,而不仅仅是挂起,但这值得一看.

You're never closing the StreamWriter... so I suspect it's not being flushed. Admittedly I'd expect an error from the server instead of just a hang, but it's worth looking at.

顺便说一句,您不需要关闭响应 并将其处置.只需using语句就足够了.

Btw, you don't need to close the response and dispose it. Just the using statement is enough.

这篇关于C#httpwebrequest getResponse()冻结并挂起我的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:49