ASP.NET-C# Post 一般处理程序(ashx)并得到返回值

var postUrl = "http://xxx.com/xxp/LoginInfo.ashx";
			var postString = "method=CheckPW&id=4454556289&pwd=&checkword=8888&sign=";
			HttpWebRequest httpRequset = null;
			HttpWebResponse httpResponse = null;
			try
			{
				//POST登录信息获取返回结果,结果为0是为登录成功
				httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//创建http 请求
				httpRequset.Method = "POST";//POST 提交
				httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在监听请求的时候都有的直接复制过来
				httpRequset.Headers.Add("X-Requested-With", "XMLHttpRequest");
				httpRequset.Accept = "*/*";
				httpRequset.Referer = "http://xxx.com/slip/Left.aspx";
				httpRequset.Headers.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.7,ja;q=0.3");
				httpRequset.Headers.Add("Accept-Encoding", "gzip, deflate");
				httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
				httpRequset.KeepAlive = true;
				httpRequset.Host = "xxx.com";
				//httpRequset.Headers.Add("Access-Control-Allow-Origin", "*");//可跨域
				httpRequset.Headers.Add("Pragma", "no-cache");
				httpRequset.Headers.Add("DNT", "1");
				httpRequset.ServicePoint.Expect100Continue = false;
				byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
				httpRequset.ContentLength = bytes.Length;
				Stream stream = httpRequset.GetRequestStream();
				stream.Write(bytes, 0, bytes.Length);
				stream.Close();//以上是POST数据的写入

				httpResponse = (HttpWebResponse)httpRequset.GetResponse();//获得 服务端响应
				var s = string.Empty;
 				using (Stream responsestream = httpResponse.GetResponseStream())
				{
					using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8))
					{
						content = sr.ReadToEnd();   //返回信息
					 
					}

WebClient 写法

WebClient webClient = new WebClient();
 
         NameValueCollection formData = new NameValueCollection();
         formData["username"] = "testuser";
         formData["password"] = "mypassword";
 
         byte[] responseBytes = webClient.UploadValues(postUrl , "POST", formData);
         string responsefromserver = Encoding.UTF8.GetString(responseBytes);
         Console.WriteLine(responsefromserver);
         webClient.Dispose();


你可能感兴趣的:(ASP.NET-C# Post 一般处理程序(ashx)并得到返回值)