首先,发送http请求,下面以发送post为例
public static HttpWebResponse CreatePostHttpResponse(string url, List<ParamBinding> parameters, int TimeOUT, string contentType = "application/x-www-form-urlencoded")
{
try
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = contentType;
request.Timeout = TimeOUT;
request.Headers.Add("Accept-Encoding", "gzip");
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
string symbol = "&";
foreach (ParamBinding key in parameters)
{
if (i > 0)
{
buffer.AppendFormat("{0}{1}={2}", symbol, key.ParaName, HttpUtility.UrlEncode(key.ParaValue != null ? key.ParaValue.ToString() : string.Empty));
}
else
{
buffer.AppendFormat("{0}={1}", key.ParaName, HttpUtility.UrlEncode(key.ParaValue != null ? key.ParaValue.ToString() : string.Empty));
i++;
}
}
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return request.GetResponse() as HttpWebResponse;
}
catch (Exception ex)
{
return null;
}
}
其次,对返回的HttpWebResponse 类型的response进行分析,这里分xml解析和stream解析
Result result = new Result();
if(response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
result = XmlHelper.GetResultFromXml(reader, requestType);
}
}
}else
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
result = XmlHelper.GetResultFromXml(reader, requestType);
}
}
}
需要注意的问题 1、如果传输的是文件,即单纯的二进制流,xml是无法进行解析的,所以需要通过“response.ContentType.Contains(“xml”)”来判断是否可以通过xml解析,一般来说如果接口不报错,但把错误写在了xml里,则需要通过以上方法进行xml解析 2、response.ContentEncoding不是gzip时,使用GZipStream方法会报错:gzip头的幻数不正确
最后,如果是单纯的stream解析 一、文件流写入文件
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
File.Delete(filePath);
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
Stream outputStream = System.IO.File.OpenWrite(filePath);
using (BinaryWriter binaryWriter = new BinaryWriter(outputStream))
{
while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
{
binaryWriter.Write(buffer, 0, count);
}
}
}
}
else
{
using (Stream stream = response.GetResponseStream())
{
File.Delete(filePath);
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
Stream outputStream = System.IO.File.OpenWrite(filePath);
using (BinaryWriter binaryWriter = new BinaryWriter(outputStream))
{
while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
{
binaryWriter.Write(buffer, 0, count);
}
}
}
}
二、如果是解析为字符串,这里的是WebResponse response
string xml = string.Empty;
using (Stream stream = response.GetResponseStream())
{
Encoding UTF8 = Encoding.GetEncoding(65001);
Encoding GBK = Encoding.GetEncoding("GBK");
Encoding GB2312 = Encoding.GetEncoding("gb2312");
switch (Code)
{
case 0:
StreamReader srUTF8 = new StreamReader(stream, System.Text.Encoding.UTF8);
xml = srUTF8.ReadToEnd();
break;
case 1:
StreamReader srGB2312 = new StreamReader(stream, GB2312);
xml = srGB2312.ReadToEnd();
break;
case 2:
StreamReader srGBK = new StreamReader(stream, GBK);
xml = srGBK.ReadToEnd();
break;
default:
StreamReader srdefault = new StreamReader(stream, System.Text.Encoding.UTF8);
xml = srdefault.ReadToEnd();
break;
}
}
文件传输流还有Deflate,和gzip一样是文件传输流 gzip是一种数据格式,默认且目前仅使用deflate算法压缩data部分; deflate是一种压缩算法,是huffman编码的一种加强。
deflate与gzip解压的代码几乎相同,可以合成一块代码。 区别仅有:
deflate使用inflateInit(),而gzip使用inflateInit2()进行初始化,比 inflateInit()多一个参数: -MAX_WBITS,表示处理raw deflate数据。因为gzip数据中的zlib压缩数据块没有zlib header的两个字节。使用inflateInit2时要求zlib库忽略zlib header。在zlib手册中要求windowBits为8…15,但是实际上其它范围的数据有特殊作用,见zlib.h中的注释,如负数表示raw deflate。 Apache的deflate变种可能也没有zlib header,需要添加假头后处理。
即MS的错误deflate (raw deflate).zlib头第1字节一般是0x78, 第2字节与第一字节合起来的双字节应能被31整除,详见rfc1950。例如Firefox的zlib假头为0x7801,python zlib.compress()结果头部为0x789c。
|