一、json格式数据提交返回
提交和返回数据都为json格式
参数提交方式:application/json;charset=UTF-8
统一采用UTF-8字符编码
public string Post(string Url, string jsonParas)
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//设置参数,并进行URL编码
string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
// String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
// Stream postData = Request.InputStream;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}
调用: string askurl = testUrl + "?sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs;
string relust = Post(askurl, "");
// 或者 string relust = Post(askurl, sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs);
二、也是josn格式,utf8
/// <summary>
/// POST数据到指定地址
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostDataToUrl(string url, System.Text.Encoding encoding, System.Collections.Specialized.NameValueCollection data)
{
//设置HttpWebRequest
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url));
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
byte[] buffer;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
for (int i = 0; i < data.Count; i++)
{
buffer = encoding.GetBytes(data.Keys[i]);
if (i > 0)
ms.WriteByte(Convert.ToByte('&'));
ms.Write(buffer, 0, buffer.Length);
ms.WriteByte(Convert.ToByte('='));
buffer = encoding.GetBytes(HttpUtility.UrlEncode(data[i]));
ms.Write(buffer, 0, buffer.Length);
}
buffer = ms.ToArray();
}
request.ContentLength = buffer.Length;
using (
System.IO.Stream requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
}
try
{
//获取数据
using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)(request.GetResponse()))
using (System.IO.Stream stream = response.GetResponseStream())
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, encoding))
{
string result = reader.ReadToEnd();
reader.Close();
stream.Close();
response.Close();
return result;
}
}
finally
{
request.Abort();
}
}
调用方法:
Byte[] bytes = Encoding.UTF8.GetBytes(msg);
//转换成Base64字符串
msg = BytesToBase64(bytes);
string encodeMsgs = System.Web.HttpUtility.UrlEncode(msg);//urlencode编码
NameValueCollection vc = new NameValueCollection();
vc.Add("sid", sid);
vc.Add("mobi", mobi);
vc.Add("sign", sign);
vc.Add("msg", encodeMsgs);
三、带证书Xml提交数据
public static string PostHttpsPost(string url, string data, string token,string sign, Encoding encoding)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//User-AgentHTTP标头的值
request.UserAgent = "Code Sample Web Client";
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "post";
if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(sign))//除了Auth接口以外其他post接口都需要传这两个参数
{
request.Headers.Add("4GGOGO-Auth-Token", token);
request.Headers.Add("HTTP-X-4GGOGO-Signature", sign);
}
request.ContentType = "text/xml";
request.Headers.Add("charset:utf-8");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Timeout = 100000;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.CookieContainer = new CookieContainer();
CookieCollection cookies = new CookieCollection();
request.CookieContainer.Add(cookies);
byte[] buffer = Encoding.UTF8.GetBytes(data);
request.ContentLength = buffer.Length;
X509Certificate cer = new X509Certificate("E:\\pdata.cer", "changeit");//证书地址和密码
request.ClientCertificates.Add(cer);
System.GC.Collect();
//如果需要POST数据
if (data != null)
{
string result = "";
//reqStream.Write(buffer, 0, buffer.Length);
//reqStream.Close();
using (System.IO.Stream requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取服务端返回数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
return result;
}
return "";
}
//调用:
string data = HelpCommon.GetAuthXml(requestTime, AppKey, signature);//获取xml字符串拼接,也可以是data序列化成xml数据
string reslut = WebUtils.PostHttpsPost(apiUrl, data, "", "", encoding);
var amodel = XmlHelper.XmlDeserialize<TrafficWebInAPI.Models.AuthModel.Response>(reslut);