【发布时间】:2014-07-06 16:16:22
【问题描述】:
当我在 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 获得相同的结果。
知道如何获得与浏览器相同的正确响应吗?
【问题讨论】: