A-A+

http请求

2015年09月20日 C#基础知识 http请求已关闭评论 阅读 289 次

/// <summary>
/// http请求
/// </summary>
public class HttpRequest
{
/// <summary>
/// POST
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="content">发送内容</param>
/// <param name="timeOut">超时时间</param>
/// <returns>结果</returns>
public static string Post(string url, string content, int timeOut)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml;charset=utf-8";
req.Timeout = timeOut * 1000;

Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(content);
req.ContentLength = data.Length;

string backstr = string.Empty;
using (Stream writer = req.GetRequestStream())
{
writer.Write(data, 0, data.Length);
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), encoding))
{
backstr = sr.ReadToEnd();
}
}
}

return backstr;
}

/// <summary>
/// ZIP发送
/// </summary>
/// <param name="url">发送地址</param>
/// <param name="content">xml内容</param>
/// <param name="timeOut">超时时间</param>
/// <returns>发送结果</returns>
public static string PostGzip(string url, string content, int timeOut)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.Headers.Add("Content-Encoding", "gzip");
req.Headers.Add("Accept-Encoding", "gzip");
req.ContentType = "text/xml;charset=utf-8";
req.Timeout = timeOut * 1000;

Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(content);
req.ContentLength = data.Length;

string backstr = string.Empty;
using (Stream writer = req.GetRequestStream())
{
writer.Write(data, 0, data.Length);
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
if (res.ContentEncoding.ToLower().Contains("gzip"))
{
using (Stream st = new GZipStream(res.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader sr = new StreamReader(st, encoding))
{
backstr = sr.ReadToEnd();
}
}
}
else
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), encoding))
{
backstr = sr.ReadToEnd();
}
}
}
}

return backstr;
}
}

标签:

评论已关闭!

Copyright © 极品飞鸽 保留所有权利.   Theme  Ality 蜀ICP备14015766号-1

用户登录

分享到: