C# Winfrom 发送 http 请求与接收 json

public static string Get(string strUrl)
{
string strResult = "";
try
{
//System.GC.Collect();
HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(strUrl);
rq.Timeout = 3000;//请求超时时间
rq.ReadWriteTimeout = 30 * 1000;//读取和写入超时时间
//rq.Proxy = null;
//rq.KeepAlive = false;
rq.Method = "GET";
rq.ContentType = "application/json; charset=UTF-8";
rq.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse rp = (HttpWebResponse)rq.GetResponse())
{
using (Stream stream = rp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
strResult = sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Get" + ex.Message);
}

return strResult;
}

public static string Post(string strUrl, Dictionary<string, string> arrDict)
{
string strResult = "";
try
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(strUrl);
hwr.Method = "POST";
hwr.ContentType = "application/x-www-form-urlencoded";
hwr.Timeout = 3000;//请求超时时间
hwr.ReadWriteTimeout = 30 * 1000;//读取和写入超时时间

byte[] byteData = DictionaryToByte(arrDict);//将提交的信息转换为byte
hwr.ContentLength = byteData.Length;

//请求数据的流
using (Stream stream = hwr.GetRequestStream())
{
//写入发送的信息
stream.Write(byteData, 0, byteData.Length);
//接收响应
using (HttpWebResponse hwrp = (HttpWebResponse)hwr.GetResponse())
{
//读取响应信息
using (StreamReader sr = new StreamReader(hwrp.GetResponseStream(), Encoding.UTF8))
{
strResult = sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Post: " + ex.Message);
}
return strResult;
}

public static byte[] DictionaryToByte(Dictionary<string, string> arrDict)
{
string strValue = "";

foreach (var item in arrDict)
{
strValue += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
}
strValue = strValue.Substring(0, strValue.LastIndexOf('&'));

return Encoding.UTF8.GetBytes(strValue);
}

posted @ 2022-05-19 18:00  海鱼No1  阅读(1019)  评论(0)    收藏  举报