c# http get请求与post请求实例

时间:2021-07-07 16:56:07

//http请求工具类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
class HttpUtil
{

/// <summary>
/// get请求
/// </summary>
/// <param name="url">网络地址</param>
/// <param name="parm">参数</param>
/// <returns></returns>
public static string HttpGet(string url,string parm){

return HttpRequest(url,parm,"GET");

}

/// <summary>
/// post请求
/// </summary>
/// <param name="url">网络地址</param>
/// <param name="parm">参数</param>
/// <returns></returns>
public static string HttpPost(string url,string parm) {

return HttpRequest(url,parm,"POST");
}

/// <summary>
/// 网络请求
/// </summary>
/// <param name="url">网络地址</param>
/// <param name="parm">参数</param>
/// <param name="method">请求方式</param>
/// <returns></returns>
private static string HttpRequest(string url, string parm, string method)
{

if(method.Equals("GET")){

url = url + "?" + parm;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Timeout = 5 * 1000;
request.AllowWriteStreamBuffering = true;
request.AllowWriteStreamBuffering = true;
request.ContentType = "text/html;charset=UTF-8";
// request.ContentType = "application/x-www-form-urlencoded";
if (method.Equals("POST"))
{
StreamWriter wr = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
wr.Write(parm);
wr.Flush();
wr.Close();
}

HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
var stream = respone.GetResponseStream();
StreamReader red = new StreamReader(stream, Encoding.UTF8);
string str = red.ReadToEnd();
red.Close();
stream.Flush();
stream.Close();
return str;
}
}
}

//调用示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(HttpUtil.HttpGet("https://hao.360.cn/?s0001",""));
}
}
}