C#Post提交
1、提交二进制流数据(json格式):
var dic = new SortedDictionary<string, string> { {"name", "test"}, {"pass", "123"}, }; //序列化参数 var jsonParam = JsonConvert.SerializeObject(dic); //发送请求 var request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; var byteData = Encoding.UTF8.GetBytes(jsonParam); var length = byteData.Length; request.ContentLength = length; var writer = request.GetRequestStream(); writer.Write(byteData, 0, length); writer.Close(); //接收数据 var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
2、提交表单方法一:
var url = "xxxxxxxxxxxxxxxxxxxxxx"; var webClientObj = new WebClient(); var postVars = new NameValueCollection { {"name", "test"}, {"pass", "123"} }; byte[] byRemoteInfo = webClientObj.UploadValues(url, "POST", postVars); string json = Encoding.UTF8.GetString(byRemoteInfo);
3、提交表单方法二:
var url = "xxxxxxxxxxxxxxxxxxxxxxx"; //通过抓包工具,可以看到是这个格式 var postData = "username=test&password=123"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Timeout = 30000; req.AllowAutoRedirect = false; req.ContentType = "application/x-www-form-urlencoded"; req.KeepAlive = true; byte[] postBytes = Encoding.UTF8.GetBytes(postData); req.ContentLength = postBytes.Length; Stream postDataStream = req.GetRequestStream(); postDataStream.Write(postBytes, 0, postBytes.Length); postDataStream.Close(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse();