需要和用户那边做数据交换,对方给了https的网址、用户名、密码等,用浏览器打开会弹出windows安全验证对话框,输入用户给的用户名和密码可以登陆成功。
现在需要用C#开发一个服务来自动实现这一系列的动作,在网上找了一堆代码,似乎都相似表单提交,需对表单中的内容提交至对方网址,但对方未提供相关的接收参数名称,怎么办?
以下是本人的代码:
现在需要用C#开发一个服务来自动实现这一系列的动作,在网上找了一堆代码,似乎都相似表单提交,需对表单中的内容提交至对方网址,但对方未提供相关的接收参数名称,怎么办?
以下是本人的代码:
private readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } public HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset) { HttpWebRequest request = null; //HTTPSQ请求 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.Proxy = null; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = DefaultUserAgent; //假如需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } byte[] data = charset.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; }
调用:
string sUrl = "https://wwwX.medion.com/zmdoa3/domaindata/ordercontract/"; Encoding encoding = Encoding.GetEncoding("utf-8"); IDictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("xuser", "****"); parameters.Add("xpasw", "****"); HttpWebResponse response = CreatePostHttpResponse(sUrl, parameters, encoding); //输出返回值 Stream stream = response.GetResponseStream(); //获取响应的字符串流 StreamReader sr = new StreamReader(stream); //创建一个stream读取流 string html = sr.ReadToEnd(); //从头读到尾,放到字符串html Response.Write(html);
parameters.Add(“xuser”, “****”);
parameters.Add(“xpasw”, “****”);
这里的xuser和xpasw是本人随便写的,对方没给,是不是对方必须提供这个才行。
解决方案
10
你这怎么看着像远程登陆服务器,不太像http啊
40
应该是需要设置WebRequest.Credentials属性,可以参考MSDN
10
post应该可以