C#中如何通过HTTP协议的不同请求方式获取数据
发布网友
发布时间:2022-12-11 08:58
我来回答
共1个回答
热心网友
时间:2024-08-25 06:16
private string GetRequest(string url)
{
string content = "";
Uri httpURL = new Uri(url);
///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
httpReq.Credentials = new NetworkCredential("***", "****");
///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容
///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
Stream respStream = httpResp.GetResponseStream();
///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以
//StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
content = respStreamReader.ReadToEnd();
return content;
}
public string PostRequest(string Paras, string Url)
{
string result = "";
HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
httpReq.Credentials = new NetworkCredential("***", "****");
string data = Paras;
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
public string DeleteRequest(string Url)
{
HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(Url);
myrequest.Method = "DELETE";
httpReq.Credentials = new NetworkCredential("***", "****");
HttpWebResponse myResponse = (HttpWebResponse)myrequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(),Encoding.UTF8);
string Return = reader.ReadToEnd();
reader.Close();
return Return;
}