/// <summary> /// 不需要返回值 /// </summary> /// <param name="strUri">地址</param> /// <param name="method">请求方式</param> /// <param name="objToSend">发送的数据(只限于Post和Put)</param> /// <param name="tick">防止等幂提交(只限于Put和Delete)</param> /// <returns></returns> public static void DoRequest(string strUri, EnumHttpMethod method, Object objToSend = null, long tick = 0) { string strToRequest = strUri; if (tick != 0 && (method == EnumHttpMethod.PUT || method == EnumHttpMethod.DELETE)) { strToRequest += "?UpdateTicks=" + tick.ToString(CultureInfo.InvariantCulture);//CultureInfo.InvariantCulture的作用是为了固定格式 } //表示一个HTTP请求消息。 HttpRequestMessage requestMsg = new HttpRequestMessage(); //设置HTTP接收请求的数据类型 requestMsg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpContentTypes.ApplicationJson)); //请求数据的链接(Uri) requestMsg.RequestUri = new Uri(strToRequest); HttpContent content = null; if (objToSend != null) { //StringContent():转换成基于字符串的HTTP内容。 //JsonConvert.SerializeObject(objToSend):将实体对象序列化成JSON content = new StringContent(JsonConvert.SerializeObject(objToSend), Encoding.UTF8, "application/json"); } switch (method) { case EnumHttpMethod.POST: requestMsg.Method = HttpMethod.Post; //Post用于新增 requestMsg.Content = content; break; case EnumHttpMethod.PUT: requestMsg.Method = HttpMethod.Put; //Put用于修改 requestMsg.Content = content; break; case EnumHttpMethod.DELETE: requestMsg.Method = HttpMethod.Delete; break; } //client是HttpClient的对象:用于发送HTTP请求和接收HTTP响应 HttpClient client = new HttpClient(); //client.SendAsync:发送一个HTTP请求一个异步操作,并返回响应结果。 Task <HttpResponseMessage> rtnAll = client.SendAsync(requestMsg); #region 执行 HttpResponseMessage resultMessage = null; try { //这一步是关键提交请求的过程,rtnAll.Result这里其实是一个多线程的处理,是.Net Framework 4.0的新特性之一 resultMessage = rtnAll.Result; } catch (AggregateException ae) { foreach (var ex in ae.InnerExceptions) { if (ex is HttpRequestException) { throw new Exception("发送网络请求失败", ex); } } } finally { client.Dispose(); } if (!resultMessage.IsSuccessStatusCode)//判断响应是否成功? { resultMessage.EnsureSuccessStatusCode(); } #endregion }
/// <summary> /// /// </summary> /// <typeparam name="T">返回转换的类型</typeparam> /// <param name="strUri">地址</param> /// <param name="method">请求方式</param> /// <param name="contentType">请求接收类型</param> /// <param name="objToSend">发送的数据(只限于Post和Put)</param> /// <param name="tick">防止等幂提交(只限于Put和Delete)</param> /// <returns></returns> public static ResponseResult <T> DoRequest <T>(string strUri, EnumHttpMethod method, EnumContentType contentType = EnumContentType.Json, Object objToSend = null, long tick = 0) { string strToRequest = strUri; if (tick != 0 && (method == EnumHttpMethod.PUT || method == EnumHttpMethod.DELETE)) { strToRequest += "?UpdateTicks=" + tick.ToString(CultureInfo.InvariantCulture);//CultureInfo.InvariantCulture的作用是为了固定格式 } //表示一个HTTP请求消息。 HttpRequestMessage requestMsg = new HttpRequestMessage(); //设置HTTP接收请求的数据类型 switch (contentType) { case EnumContentType.Json: requestMsg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpContentTypes.ApplicationJson)); break; case EnumContentType.Xml: requestMsg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpContentTypes.ApplicationXml)); break; } //请求数据的链接(Uri) requestMsg.RequestUri = new Uri(strToRequest); HttpContent content = null; if (objToSend != null) { //StringContent():转换成基于字符串的HTTP内容。 //JsonConvert.SerializeObject(objToSend):将实体对象序列化成JSON switch (contentType) { case EnumContentType.Json: content = new StringContent(JsonConvert.SerializeObject(objToSend), Encoding.UTF8, "application/json"); break; case EnumContentType.Xml: content = new StringContent(SerializeUtil.SerializeToXml(objToSend), Encoding.UTF8, "application/xml"); break; case EnumContentType.String: content = new StringContent(objToSend.ToString()); break; } } switch (method) { case EnumHttpMethod.POST: requestMsg.Method = HttpMethod.Post; //Post用于新增 requestMsg.Content = content; break; case EnumHttpMethod.PUT: requestMsg.Method = HttpMethod.Put; //Put用于修改 requestMsg.Content = content; break; case EnumHttpMethod.DELETE: requestMsg.Method = HttpMethod.Delete; break; default: requestMsg.Method = HttpMethod.Get; //Get用于获取 break; } //client是HttpClient的对象:用于发送HTTP请求和接收HTTP响应 HttpClient client = new HttpClient(); //client.SendAsync:发送一个HTTP请求一个异步操作,并返回响应结果。 Task <HttpResponseMessage> rtnAll = client.SendAsync(requestMsg); #region 执行 HttpResponseMessage resultMessage = null; Task <T> rtnFinal; try { //这一步是关键提交请求的过程,rtnAll.Result这里其实是一个多线程的处理,是.Net Framework 4.0的新特性之一 resultMessage = rtnAll.Result; } catch (AggregateException ae) { foreach (var ex in ae.InnerExceptions) { if (ex is HttpRequestException) { throw new Exception("发送网络请求失败", ex); } } } finally { client.Dispose(); } if (!resultMessage.IsSuccessStatusCode)//判断响应是否成功? { resultMessage.EnsureSuccessStatusCode(); } try { switch (contentType) { case EnumContentType.Xml: rtnFinal = resultMessage.Content.ReadAsAsync <T>(new MediaTypeFormatter[] { new XmlMediaTypeFormatter() }); break; default: rtnFinal = resultMessage.Content.ReadAsAsync <T>(new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }); break; } } catch (Exception ex) { throw new Exception("服务器返回与请求不匹配", ex); } #endregion return(new ResponseResult <T>() { Value = rtnFinal.Result, RawValue = resultMessage.Content.ReadAsStringAsync().Result }); }
/// <summary> /// Accept HTTP header line. /// Processing and filling /// </summary> /// <param name="startingLine">text of HTTP header line</param> private void ParseStartingLine(string startingLine) { // Parsing HTTPversion if (startingLine.StartsWith("GET")) { _httpMethod = EnumHttpMethod.GET; } else { if (startingLine.StartsWith("POST")) { _httpMethod = EnumHttpMethod.POST; } else { _httpMethod = EnumHttpMethod.UNKNOWN; } } // Console.WriteLine(HttpMethod); // Parsing HTML version httpVersion = Helpers.WebserverConstants.Unknown; if (startingLine.Contains(Helpers.WebserverConstants.HttpVersion11)) { httpVersion = Helpers.WebserverConstants.HttpVersion11; } else if (startingLine.Contains(Helpers.WebserverConstants.HttpVersion10)) { httpVersion = Helpers.WebserverConstants.HttpVersion10; } // Console.WriteLine(httpVersion); // Parsing path string pathLine = startingLine.Substring(startingLine.IndexOf("/")); httpPath = pathLine.Substring(0, pathLine.IndexOf(" ")); // Console.WriteLine(httpPath); }
/// <summary> /// Constructor of Request class /// </summary> public Request() { this._httpMethod = EnumHttpMethod.UNKNOWN; this.httpVersion = "Unknown"; hasRange = false; hasCookie = false; }
/// <summary> /// Http (GET/POST) 异步 /// </summary> /// <param name="url">请求URL</param> /// <param name="param">请求参数</param> /// <param name="method">请求方法</param> /// <param name="contentType">响应类型</param> /// <param name="encoding">编码方式</param> /// <param name="timeout">超时时间(单位:毫秒)</param> /// <returns></returns> public static string RequestAsync(string url, string param, EnumHttpMethod method, string contentType = "application/json", Encoding encoding = null, int timeout = 10000) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (string.IsNullOrEmpty(contentType)) { if (method == EnumHttpMethod.Post) { contentType = "application/x-www-form-urlencoded"; } if (method == EnumHttpMethod.Get) { contentType = "text/html"; } } encoding = encoding ?? Encoding.UTF8; if (!contentType.Contains("charset")) { if (contentType.Substring(contentType.Length - 1, 1) == ";") { contentType = contentType + "charset=" + encoding.WebName; } else { contentType = contentType + ";charset=" + encoding.WebName; } } if (!string.IsNullOrEmpty(param)) { if (JsonHelper.IsJson(param)) { } else { //不是json var paramArr = param.Split('&').ToList(); var paramList = new List <Tuple <string, string> >(); foreach (var item in paramArr) { var k = item.Split('=')[0]; var v = item.Split('=')[1]; paramList.Add(new Tuple <string, string>(k, HttpUtility.UrlEncode(v, encoding))); } var paramTemp = (from p in paramList select p.Item1 + "=" + p.Item2).ToList(); var paramStr = string.Join("&", paramTemp); param = paramStr; } if (method == EnumHttpMethod.Get) { var split = url.Contains("?") ? "&" : "?"; url = url + split + param; } } var webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; webRequest.Method = method.ToString().ToUpper(); var strResponse = string.Empty; if (method == EnumHttpMethod.Post) { webRequest.Timeout = timeout; webRequest.ProtocolVersion = HttpVersion.Version10; webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.ContentType = contentType; if (!string.IsNullOrEmpty(param)) { byte[] bytes = encoding.GetBytes(param); using (var stream = webRequest.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); } } } else if (method == EnumHttpMethod.Get) { webRequest.ReadWriteTimeout = timeout; webRequest.ContentType = contentType; } var complete = false; var stime = DateTime.Now; var asyncResult = webRequest.BeginGetResponse(new AsyncCallback(t => { using (var webResponse = webRequest.EndGetResponse(t)) { using (var webStream = webResponse.GetResponseStream()) { if (webResponse.Headers.Get("Content-Encoding") == "gzip") { using (GZipStream gzip = new GZipStream(webStream, CompressionMode.Decompress)) { using (var reader = new StreamReader(gzip, encoding)) { strResponse = reader.ReadToEndAsync().Result; complete = true; } } } else { using (var streamReader = new StreamReader(webStream, encoding)) { strResponse = streamReader.ReadToEndAsync().Result; complete = true; } } } } }), null); while (!complete && (DateTime.Now - stime).TotalMilliseconds < timeout) { } return(strResponse); }
/// <summary> /// Http (GET/POST) /// </summary> /// <param name="url">请求URL</param> /// <param name="parameters">请求参数</param> /// <param name="method">请求方法</param> /// <returns>响应内容</returns> public static string Request(string url, IDictionary <string, string> parameters, EnumHttpMethod method) { string jsonStr = string.Empty; if (method == EnumHttpMethod.Post) { HttpWebRequest req = null; HttpWebResponse rsp = null; Stream reqStream = null; req = (HttpWebRequest)WebRequest.Create(url); req.Method = method.ToString(); req.KeepAlive = false; req.ProtocolVersion = HttpVersion.Version10; req.Timeout = 10000; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8")); reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(string.IsNullOrEmpty(rsp.CharacterSet) ? "utf-8" : rsp.CharacterSet); jsonStr = GetResponseAsString(rsp, encoding); return(jsonStr); } else { //创建请求 if (url.Contains("?")) { url = url + "&" + BuildQuery(parameters, "utf8"); } else { url = url + "?" + BuildQuery(parameters, "utf8"); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //GET请求 request.Method = "GET"; request.ReadWriteTimeout = 5000; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); //返回内容 jsonStr = myStreamReader.ReadToEnd(); return(jsonStr); } }
/// <summary> /// Http (GET/POST) 异步 /// </summary> /// <param name="url">请求URL</param> /// <param name="param">请求参数 key:参数名 value:参数值</param> /// <param name="method">请求方法</param> /// <param name="contentType">响应类型</param> /// <param name="encoding">编码方式</param> /// <param name="timeout">超时时间</param> /// <returns></returns> public static string RequestAsync(string url, IDictionary <string, object> param, EnumHttpMethod method, string contentType = "application/json", Encoding encoding = null, int timeout = 10000) { var paramTemp = (from p in param select p.Key + "=" + p.Value.ToString()).ToList(); var paramStr = string.Join("&", paramTemp); return(RequestAsync(url, paramStr, method, contentType, encoding, timeout)); }