You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/Areas/MvcShipping/Comm/XMLHelper.cs

251 lines
9.6 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Net;
using System.IO.Compression;
namespace DSWeb.Areas.MvcShipping.Comm
{
public static class WebRequestHelper
{
public static string DoGet(string url)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
req.ContentLength = 0;
var response = req.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseString = streamRead.ReadToEnd();
response.Close();
streamRead.Close();
return responseString;
}
public static string DoPost(string url, string json, int timeout = 10000)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.Timeout = timeout;
req.Headers.Add("Accept-Encoding", "gzip, deflate");
if (!string.IsNullOrWhiteSpace(json))
{
byte[] postBytes = Encoding.UTF8.GetBytes(json);
req.ContentType = "application/json; charset=utf-8";
req.ContentLength = Encoding.UTF8.GetByteCount(json);
Stream stream = req.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
}
else
{
req.ContentLength = 0;
}
var response = req.GetResponse();
responseString = GetResponseBody((HttpWebResponse)response);
return responseString;
}
public static string DoPost(string url, Dictionary<string, string> dic, int timeout = 10000)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.Timeout = timeout;
req.Headers.Add("Accept-Encoding", "gzip, deflate");
if (dic.Count > 0)
{
string strContent = string.Empty;
foreach (var item in dic)
{
if (strContent.Length > 0)
{
strContent += "&";
}
strContent += $"{item.Key}={item.Value}";
}
byte[] postBytes = Encoding.UTF8.GetBytes(strContent);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream stream = req.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
}
else
{
req.ContentLength = 0;
}
var response = req.GetResponse();
responseString = GetResponseBody((HttpWebResponse)response);
return responseString;
}
private static string GetResponseBody(HttpWebResponse response)
{
string responseBody = string.Empty;
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
responseBody = reader.ReadToEnd();
}
}
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(
response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader =
new StreamReader(stream, Encoding.UTF8))
{
responseBody = reader.ReadToEnd();
}
}
}
else
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
responseBody = reader.ReadToEnd();
}
}
}
return responseBody;
}
}
public static class XmlHelper
{
private static string NAMESPACE = "http://HCHX.Schemas.";
private static void XmlSerializeInternal ( Stream stream, object o, Encoding encoding,string ip)
{
if (o == null)
throw new ArgumentNullException("o");
if (encoding == null)
throw new ArgumentNullException("encoding");
XmlSerializer serializer = new XmlSerializer(o.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.IndentChars = " ";
settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("ns", ip);
serializer.Serialize(writer, o, namespaces);
writer.Close();
}
}
/// <summary>
/// 将一个对象序列化为XML字符串
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="encoding">编码方式</param>
/// <param name="nameSpace">命名空间</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerialize ( object o, Encoding encoding, string nameSpace,string ip )
{
NAMESPACE = NAMESPACE + nameSpace;
using (MemoryStream stream = new MemoryStream())
{
XmlSerializeInternal(stream, o, encoding,ip);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 将一个对象按XML序列化的方式写入到一个文件
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="path">保存文件路径</param>
/// <param name="encoding">编码方式</param>
public static void XmlSerializeToFile ( object o, string path, Encoding encoding, string nameSpace ,string ip)
{
NAMESPACE = NAMESPACE + nameSpace;
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
XmlSerializeInternal(file, o, encoding,ip);
}
}
/// <summary>
/// 从XML字符串中反序列化对象
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="s">包含对象的XML字符串</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserialize<T> ( string s, Encoding encoding )
{
if (string.IsNullOrEmpty(s))
throw new ArgumentNullException("s");
if (encoding == null)
throw new ArgumentNullException("encoding");
XmlSerializer mySerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
{
using (StreamReader sr = new StreamReader(ms, encoding))
{
return (T)mySerializer.Deserialize(sr);
}
}
}
/// <summary>
/// 读入一个文件并按XML的方式反序列化对象。
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="path">文件路径</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserializeFromFile<T> ( string path, Encoding encoding )
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
string xml = File.ReadAllText(path, encoding);
return XmlDeserialize<T>(xml, encoding);
}
}
}