using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text;
namespace Tt.KD100.Initiative.WinService { /// <summary> /// 请求信息帮助 /// </summary> public class HttpHelper { /// <summary> /// post 请求指定地址返回响应数据 /// </summary> /// <param name="url">请求地址</param> /// <param name="postData">请求数据</param> /// <param name="timeout">请求超时时间(毫秒)</param> /// <param name="requestCoding">请求编码</param> /// <param name="responseCoding">响应编码</param> /// <returns></returns> public string PostRequest(string url, Dictionary<string, string> postData, int timeout,Encoding requestCoding, Encoding responseCoding) { string postStr = string.Empty; if (postData!=null) { postData.All(o => { if (string.IsNullOrEmpty(postStr)) postStr = string.Format("{0}={1}", o.Key, o.Value); else postStr += string.Format("&{0}={1}", o.Key, o.Value);
return true; }); } return PostRequest(url, postStr,timeout, requestCoding, responseCoding); } /// <summary> /// post 请求指定地址返回响应数据 /// </summary> /// <param name="url">请求地址</param> /// <param name="postData">请求数据</param> /// <param name="timeout">请求超时时间(毫秒)</param> /// <param name="requestCoding">请求编码</param> /// <param name="responseCoding">响应编码</param> /// <returns></returns> public string PostRequest(string url, string postData,int timeout, Encoding requestCoding,Encoding responseCoding) { string postUrl = VerifyUrl(url); try { //写入POSTDATE里 byte[] byteArray = requestCoding.GetBytes(postData); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); webRequest.Method = "POST"; webRequest.Timeout = timeout; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream newStream = webRequest.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); //接收返回信息: HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); StreamReader php = new StreamReader(response.GetResponseStream(), responseCoding); string result = php.ReadToEnd(); return result; } catch (Exception ex) { Grass.Log.ExceptionsStack.RegisterError(ex); return string.Empty; } } /// <summary> /// 验证URL /// </summary> /// <param name="url">待验证 URL</param> /// <returns></returns> private string VerifyUrl(string url) { if(string.IsNullOrEmpty(url)) throw new Exception("URL 地址不可以为空!");
if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase)) return url;
return string.Format("http://{1}", url); } } }
转载于:https://www.cnblogs.com/xxj-jing/archive/2012/10/24/2890044.html
相关资源:C#利用post访问接口