当前位置 : 主页 > 网页制作 > HTTP/TCP >

连接微服务

来源:互联网 收集:自由互联 发布时间:2021-06-16
连接微服务,json传输 public static string HttpPost(string posturl, string postData, string method = "POST", string contentType = "application/json") { Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] data = encoding.GetByte

连接微服务,json传输

public static string HttpPost(string posturl, string postData, string method = "POST", string contentType = "application/json")
{
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] data = encoding.GetBytes(postData);
try
{
// 设置参数
HttpWebRequest request = WebRequest.Create(posturl) as HttpWebRequest;
//增加下面两个属性即可
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.ServicePoint.Expect100Continue = false;
request.ContentType = contentType;
request.ContentLength = data.Length;
byte[] buffer = encoding.GetBytes(postData); // 数据编码UTF-8格式
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return string.Empty;
}
}

传输string

public static string Http(string Url, string Data, string Method) { HttpHelper http = new HttpHelper(); HttpItem item = new HttpItem() { URL = Url,//URL 必需项 Method = Method,//URL 可选项 默认为Get IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写 Cookie = "",//字符串Cookie 可选项 Referer = "",//来源URL 可选项 Postdata = Data,//Post数据 可选项GET时不需要写 Timeout = 100000,//连接超时时间 可选项默认为100000 ReadWriteTimeout = 30000,//写入Post数据超时时间 可选项默认为30000 UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型,版本,操作系统 可选项有默认值 ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值 Allowautoredirect = false,//是否根据301跳转 可选项 //CerPath = "d:\123.cer",//证书绝对路径 可选项不需要证书时可以不写这个参数 //Connectionlimit = 1024,//最大连接数 可选项 默认为1024 ProxyIp = "",//代理服务器ID 可选项 不需要代理 时可以不设置这三个参数 //ProxyPwd = "123456",//代理服务器密码 可选项 //ProxyUserName = "administrator",//代理服务器账户名 可选项 ResultType = ResultType.String }; HttpResult result = http.GetHtml(item); string html = result.Html; string cookie = result.Cookie; return html; }

网友评论