[英]how to GET data using HttpWebRequest
I am working getting data using HttpWebRequest and run into stream not readable error using the below code.我正在使用 HttpWebRequest 获取数据并使用以下代码遇到 stream 不可读错误。
JavaScriptSerializer jss = new JavaScriptSerializer();
string getUrl = "http://url.com";
var getdata = "";
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(getUrl);
webrequest.Method = "GET";
webrequest.ContentType = "application/json";
webrequest.ContentLength = data.Length;
using (HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse())
using (Stream stream = webresponse.GetResponseStream())
using (StreamReader reader = new StreamReader(stream)) //stream not readable error
{
getdata = reader.ReadToEnd();
}
dynamic getjsondata = jss.Deserialize<dynamic>(getdata);
Not sure where I am doing it wrong.不知道我在哪里做错了。
Don't supply ContentType
or ContentLength
for an HTTP Get, the server does that in the response.不要为 HTTP Get 提供ContentType
或ContentLength
,服务器会在响应中执行此操作。
In your first using
statement, you're calling a different request
object.在您的第一个using
语句中,您调用了一个不同的request
object。
Try this (no exception handling included):试试这个(不包括异常处理):
JavaScriptSerializer jss = new JavaScriptSerializer();
string getUrl = "http://url.com";
var getdata = "";
HttpWebRequest webRequest = WebRequest.CreateHttp(getUrl);
//webrequest.Method = "GET"; // GET is the default.
using (var webResponse = webRequest.GetResponse())
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
getdata = reader.ReadToEnd();
}
dynamic getjsondata = jss.Deserialize<dynamic>(getdata);
You could add an accept header if needed by the endpoint though:如果端点需要,您可以添加接受 header :
webRequest.Accept = "application/json";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.