C# 使用HttpWebRequest Post提交数据,携带Cookie和相关参数示例
2021-05-05 18:33
标签:static read ica sms 网页 pass gecko form 控制 C# 使用HttpWebRequest Post提交数据,携带Cookie和相关参数示例 标签:static read ica sms 网页 pass gecko form 控制 原文地址:http://www.cnblogs.com/smartsmile/p/7676728.htmlusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.Net;
using System.IO;
namespace Sample2
{
class Program
{
static void Main(string[] args)
{
try
{
//data
string cookieStr = "51fd9f14fa7561b5";
string postData = string.Format("userid={0}&password={1}", "guest", "123456");
byte[] data = Encoding.UTF8.GetBytes(postData);
// Prepare web request...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.xxx.com");
request.Method = "POST";
//request.Referer = "https://www.xxx.com";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
//request.Host = "www.xxx.com";
request.Headers.Add("Cookie", cookieStr);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
}
}
///
class Program
{
static void Main(string[] args)
{
var str = DownloadStringAsync(new Uri("http://www.baidu.com"));
Console.WriteLine(str.Result);
Console.ReadLine();
}
static async Taskstring> DownloadStringAsync(Uri uri)
{
//WebClient 不支持超时设定
//而HttpWebRequst则允许你设置请求头或者对内容需要更多的控制
var webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
var result = await webClient.DownloadStringTaskAsync(uri);
return result;
}
}
文章标题:C# 使用HttpWebRequest Post提交数据,携带Cookie和相关参数示例
文章链接:http://soscw.com/essay/82861.html