C# http请求数据

时间:2023-08-13 22:36:26

http中get和post请求的最大区别:get是通过URL传递表单值,post传递的表单值是隐藏到 http报文体中

http以get方式请求数据

        /// <summary>
/// get请求
/// </summary>
/// <param name="url">地址</param>
/// <returns></returns>
public string HttpGetRequest(string url)
{
//创建请求
HttpWebRequest request =
WebRequest.Create(url) as
HttpWebRequest;
string json = ""; //得到请求的返回数据
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK) //表示返回的状态吗是200,请求成功
{
//得到返回的数据流,进行读取
using (Stream streamResonse = response.GetResponseStream())
using (StreamReader reader = new StreamReader(streamResonse))
{ json = reader.ReadToEnd();
}
}
} return json;
}

http以post方式请求数据

 /// <summary>
/// post请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="parameters">数据参数</param>
/// <returns></returns>
public string HttpPostRequest(string url, IDictionary<string, object> parameters)
{
//创建请求
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; //序列化--参数传递使用json传递
string jsonRes = JsonConvert.SerializeObject(parameters); //发送请求数据
byte[] data = Encoding.Default.GetBytes(jsonRes);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, , data.Length);
} string json = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK) //
{
using (Stream streamResonse = response.GetResponseStream())
using (StreamReader reader = new StreamReader(streamResonse))
{ json = reader.ReadToEnd();
}
}
} return json;
}