一.
private void button1_Click(object sender, EventArgs e) { string url = "localhost"; byte[] responseArray = null; using (WebClient webClient = new WebClient()) { webClient.Headers.Add("jsonStr", ""); NameValueCollection postValues = new NameValueCollection(); responseArray = webClient.UploadValues(url, postValues); } string response = Encoding.UTF8.GetString(responseArray); if (!string.IsNullOrEmpty(response) && !response.Equals("null")) { //result = JsonConvert.DeserializeObject<BaseElseResut>(response); //if (result != null && result.Data != null && result.Data.success) //{ // Response.Write("<script language=javascript>window.location.href='" + result.Data.Reason + "';</script>"); //} //else //{ // Response.Write("<script>alert('" + result.Data.Reason + "');</script>"); //} } }
二、
public string aa() { string url = "http://localhost"; byte[] responseArray = null; using (WebClient webClient = new WebClient()) { webClient.Headers.Add("usercode", "a"); webClient.Headers.Add("username", "b"); NameValueCollection postValues = new NameValueCollection(); postValues.Add("a", a); postValues.Add("b", b); postValues.Add("c", c); postValues.Add("d", d); postValues.Add("c", c); responseArray = webClient.UploadValues(url, postValues); } string response = Encoding.UTF8.GetString(responseArray); if (!string.IsNullOrEmpty(response) && !response.Equals("null")) { result = JsonConvert.DeserializeObject<BaseElseResut>(response); } }
三、
public void PostTest() { string url = "http://localhost:8009/"; Dictionary<string, object> dic = null; string strParams = JsonConvert.SerializeObject(dic);//ParsToString(pairs); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //请求方式POST request.Method = "POST"; //传输数据JSON类型 request.ContentType = "application/json;charset=utf-8"; request.Credentials = CredentialCache.DefaultCredentials; byte[] bytes = Encoding.Default.GetBytes("userName:Password"); var strAuthorization = Convert.ToBase64String(bytes); request.Headers.Add("Authorization", strAuthorization); //请求超时时间,10分钟 request.Timeout = 600000; AddHeaderParams(request); //写入数据 var data = Encoding.UTF8.GetBytes(strParams); request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); //请求返回数据 StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8); string ret = reader.ReadToEnd(); reader.Close(); } /// <summary> /// 添加通用的Header参数 /// </summary> /// <returns></returns> private void AddHeaderParams(HttpWebRequest request) { Dictionary<string, string> pairs = new Dictionary<string, string>() { { "a", "1" } , { "b", "2" }, { "c", "3" }, { "d", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} }; foreach (string key in pairs.Keys) { request.Headers.Add(key, pairs[key]); } }
四、