我有一个http长期存在的Web服务。如果它有新数据,它将使用http GET推送到客户端。如何通过HttpWebRequest c#?
从http长期Web服务接收实时数据答案 0 :(得分:0)
如果您想使用Get获取数据,可以使用此方法(使用GetResponse时响应是同步的):
public string GetMessageViaGet(string endPoint)
{
HttpWebRequest request = CreateWebRequest(endPoint);
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
private HttpWebRequest CreateWebRequest(string endPoint)
{
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "text/xml";
return request;
}
答案 1 :(得分:0)
如果您想通过邮件获取数据,请执行此操作
public string GetMessageViaPost(string endPoint, string paramtersJson)
{
string responseValue;
byte[] bytes = Encoding.UTF8.GetBytes(paramtersJson);
HttpWebRequest request = CreateWebRequest(endPoint, bytes.Length);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
return responseValue;
}
private HttpWebRequest CreateWebRequest(string endPoint, Int32 contentLength)
{
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "POST";
request.ContentLength = contentLength;
request.ContentType = "application/json";// "application/x-www-form-urlencoded";
return request;
}