2015-02-04 1 views
3

Я не могу сделать запрос на отправку по URL-адресу с помощью HttpWebRequest. Я применил все предложения, которые я видел в Интернете. Большинство ответов на SO предлагают указание агента пользователя. Я сделал это и предоставил тайм-аут, но все же у меня есть тайм-аут. Я увидел еще одну запись, где упоминалось, чтобы вместо этого было указано readwritetimeout. Тем не менее, я получаю тот же ответ, «Server Timed out». Создание сообщения с помощью браузера работает в течение секунды, но использование кода в C# дает проблему с таймаутом. Вот мой код:HttpWebRequest.GetResponse всегда разыгрывает вне зависимости от того, что

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2288.6 Safari/537.36"; 
     request.Method = "POST"; 
     request.KeepAlive = true; 
     request.CookieContainer = new CookieContainer(); 
     request.Accept = "*/*"; 
     request.ReadWriteTimeout = System.Threading.Timeout.Infinite; 
     request.Headers.Add("Accept-Encoding: gzip, deflate"); 
     request.Headers.Add("Accept-Language: en-US"); 
     byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
     request.ContentLength = byteArray.Length; 
     Stream dataStream = request.GetRequestStream(); 
     dataStream.Write(byteArray, 0, byteArray.Length); 
     dataStream.Close(); 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     dataStream = response.GetResponseStream(); 
     StreamReader reader = new StreamReader(dataStream); 
     string Response = reader.ReadToEnd(); 

Я получаю тайм-аут на этой линии:

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

я упускаю что-то здесь?

Вот журнал после включения диагонали в конфигурации.

System.Net Verbose: 0 : [0280] WebRequest::Create(http://mysite.url.here) 
System.Net Verbose: 0 : [0280] HttpWebRequest#13062350::HttpWebRequest(http://mysite.url.here) 
System.Net Information: 0 : [0280] Current OS installation type is 'Client'. 
System.Net Information: 0 : [0280] RAS supported: True 
System.Net Verbose: 0 : [0280] Exiting HttpWebRequest#13062350::HttpWebRequest() 

System.Net Verbose: 0 : [0280] Exiting WebRequest::Create()  -> HttpWebRequest#13062350 
System.Net Error: 0 : [0280] Can't retrieve proxy settings for Uri 'http://mysite.url.here'. Error code: 12180. 
System.Net Verbose: 0 : [0280] ServicePoint#10366524::ServicePoint(http://mysite.url.here:80) 
System.Net Information: 0 : [0280] Associating HttpWebRequest#13062350 with ServicePoint#10366524 
System.Net Verbose: 0 : [0280] HttpWebRequest#13062350::GetRequestStream() 
System.Net Information: 0 : [0280] Associating Connection#63840421 with HttpWebRequest#13062350 
System.Net Information: 0 : [0280] Connection#63840421 - Created connection from 192.168.1.5:13902 to 199.249.234.200:80. 
System.Net Information: 0 : [0280] Associating HttpWebRequest#13062350 with ConnectStream#54246671 
System.Net Information: 0 : [0280] HttpWebRequest#13062350 - Request: POST /Post-url-here HTTP/1.1 

System.Net Information: 0 : [0280] ConnectStream#54246671 - Sending headers 
{ 
Content-Type: application/x-www-form-urlencoded 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, likeGecko) Chrome/42.0.2288.6 Safari/537.36 
Accept-Encoding: gzip, deflate 
Accept-Language: en-US 
Cache-Control: max-age=0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 
Host: www.powersportrider.com 
Content-Length: 101 
Expect: 100-continue 
Connection: Keep-Alive 
}. 

System.Net Verbose: 0 : [0280] Exiting ConnectStream#54246671::Write() 
System.Net Verbose: 0 : [0280] ConnectStream#54246671::Close() 
System.Net Verbose: 0 : [0280] Exiting ConnectStream#54246671::Close() 
System.Net Verbose: 0 : [0280] HttpWebRequest#13062350::GetResponse() 
System.Net Information: 0 : [0280] Connection#63840421 - Received status line: V 
ersion=1.1, StatusCode=100, StatusDescription=Continue. 
System.Net Information: 0 : [0280] Connection#63840421 - Received headers 
{ 

}. 


System.Net Verbose: 0 : [8668] HttpWebRequest#13062350::Abort(The operation hastimed out) 
System.Net Verbose: 0 : [8668] Exiting HttpWebRequest#13062350::Abort() 
System.Net Error: 0 : [0280] Exception in HttpWebRequest#13062350:: - The operation has timed out. 
System.Net Error: 0 : [0280] Exception in HttpWebRequest#13062350::GetResponse - The operation has timed out. 
System.Net Error: 0 : [0280] Exception in AppDomain#12036987::UnhandledException 
Handler - The operation has timed out. at System.Net.HttpWebRequest.GetResponse() 

ответ

4

Оказывается, все, что мне нужно сделать, чтобы получить эту работу было добавить следующие строки перед вызовом request.GetResponse()

request.ServicePoint.Expect100Continue = false; 
request.ProtocolVersion = HttpVersion.Version11; 

надеюсь, что часы, проведенные на это помогает кто-то еще быстрее.

0

У меня была такая же проблема. Для меня исправление было так же просто, как обертывание кода HttpWebResponse при использовании блока.

using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) 
{ 
    // Do your processings here.... 
} 

Эта проблема обычно происходит, если вы сделаете несколько запросов на тот же хост, и WebResponse не расположена должным образом. Вот почему блок использования приходит сюда как спаситель.

Смежные вопросы