开发者

getResponse in c# not working. No response coming back

I have this code in C#:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 30000; 
request.Method = "POST"; 
request.KeepAlive = true;
request.AllowAutoRedirect = false;

Stream newStream = request开发者_如何学编程.GetRequestStream();
newStream.Write(bPostData, 0, bPostData.Length);

byte[] buf = new byte[1025]; int read = 0; string sResp = "";
HttpWebResponse wResp = (HttpWebResponse)request.GetResponse();
Stream resp = wResp.GetResponseStream();

The line HttpWebResponse wResp =... just hangs (as in no response from the URL). I'm not sure where exactly its crashing (cause i dont even get an exception error). I tested the URL in IE and it works fine. I also checked the bPostData and that one has data in it. Where is it going wrong?


Try closing the request stream in variable newStream. Maybe the API waits for it to be done.


You have to increase the limit:

ServicePointManager.DefaultConnectionLimit = 10; // Max number of requests


Try simplifying your code and faking a user agent. Maybe the site is blocking/throttling scrapers/bots. Also ensure your application/x-www-form-urlencoded HTTP POST values are properly encoded. For this I would recommend you WebClient:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
    };
    byte[] result = client.UploadValues(url, values);
}


When I commented earlier, I had run your code at my office (heavily firewalled) I got the same result you did. Came home, tried again (less firewalled) it worked fine... I'm guessing you have a barrier there. I believe you are facing a firewall issue.


Use a content-length=0

Example:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
        request.Method = "POST";
        request.ContentLength = 0;
        var requestStream = request.GetRequestStream();
        HttpWebResponse res = (HttpWebResponse)request.GetResponse();
        res.Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜