远程服务器使用webrequest返回错误(400)错误请求

时间:2014-07-06 16:16:22

标签: asp.net httpwebrequest

当我在URL上执行HttpWebRequest.GetResponse时,GetResponse返回"远程服务器返回错误:(400)错误请求。"而不是回应。

奇怪的是,当我在浏览器中运行此网址时,我得到正确的回复

webrequest不需要返回与浏览器相同的值吗?

以下代码返回错误请求

 // Create a request for the URL. 
            WebRequest request = WebRequest.Create(
              "http://someUrl/api/v5/basicAuth");


            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();

也尝试使用具有相同结果的WebClient。

任何想法如何获得与浏览器相同的正确响应?

1 个答案:

答案 0 :(得分:0)

标题显示您收到了400条错误请求,但在您的问题中,您说404 Not Found。那些是非常不同的。对于404,我会对URL本身以及请求如何路由,DNS等进行故障排除,如果它是400,那么我会使用类似Fiddler的东西来捕获我的请求在使用时的外观浏览器,然后看看来自该程序的请求是什么样的,看看有什么不同/缺失。可能需要一些HTTP头,例如内容类型,或者处理cookie等等。但像Fiddler这样的东西至少可以让你开始。

相关问题