public static bool RequestWithXmldata(out HttpWebResponse response, string url, HttpType method, string data) { response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString(); response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; } else { return(false); } } catch (Exception) { if (response != null) { response.Close(); } return(false); } return(true); }
/// <summary> /// Return Response Code /// </summary> /// <param name="url"></param> /// <param name="httpType"></param> /// <returns></returns> public int GetResponseCode(string url, HttpType httpType) { Log.Debug("{httpType} ::: {url}", url, httpType); var request = (HttpWebRequest) WebRequest.Create(url); request.Method = httpType.ToString().ToUpper(); HttpWebResponse response; try { if (httpType == HttpType.Post) { var encoding = new ASCIIEncoding(); var bytesToWrite = encoding.GetBytes(string.Empty); request.ContentLength = bytesToWrite.Length; } response = (HttpWebResponse) request.GetResponse(); } catch { return (int) Constants.HttpStatusCode.NotFound; } var status = response.StatusCode; return (int) status; }
/// <summary> /// Return Response Code /// </summary> /// <param name="url"></param> /// <param name="httpType"></param> /// <returns></returns> public int GetResponseCode(string url, HttpType httpType) { Log.Debug("{httpType} ::: {url}", url, httpType); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = httpType.ToString().ToUpper(); HttpWebResponse response; try { if (httpType == HttpType.Post) { var encoding = new ASCIIEncoding(); var bytesToWrite = encoding.GetBytes(string.Empty); request.ContentLength = bytesToWrite.Length; } response = (HttpWebResponse)request.GetResponse(); } catch { return((int)Constants.HttpStatusCode.NotFound); } var status = response.StatusCode; return((int)status); }
public Dictionary <string, string> ToReplacementDictionary(Dictionary <string, string> dct) { dct.Add("$aurelia_project_name$", AureliaProjectName); dct.Add("$aurelia_module_loader$", ModuleLoader.ToString()); dct.Add("$aurelia_http_type$", HttpType.ToString()); dct.Add("$aurelia_transpiler$", Transpiler.ToString()); dct.Add("$aurelia_minification$", Minification.ToString()); dct.Add("$aurelia_css_processing$", CSSProcessing.ToString()); dct.Add("$aurelia_unit_ruinner$", UnitTestRunner.ToString()); dct.Add("$aurelia_integration_testing$", IntegrationTesting.ToString()); dct.Add("$aurelia_install_after$", InstallAfter.ToString()); dct.Add("$aurelia_build_after$", BuildAfter.ToString()); return(dct); }
public static bool Request(out HttpWebResponse response, string url, HttpType method, Dictionary <string, string> data) { response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString(); if (data != null) { foreach (var i in data) { request.Headers.Set(i.Key, i.Value); } } response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; } else { return(false); } } catch (Exception) { if (response != null) { response.Close(); } return(false); } return(true); }
/// <summary> /// 访问接口并返回OperateResult类型对象及数据 /// </summary> /// <typeparam name="T1">OperateResult类型对象</typeparam> /// <typeparam name="T2">数据</typeparam> /// <param name="url">接口地址</param> /// <param name="type">访问类型,HttpType</param> /// <param name="param">参数,对象形式自动转换,或json字符串</param> /// <param name="replaceList">替换数组</param> /// <param name="standardResult">是否返回标准的OperateResult,默认是,false则会自动组装</param> /// <param name="timeOut">超时时间</param> /// <returns>返回OperateResult类型对象及数据</returns> public T1 HttpRequest <T1, T2>(string url, HttpType type = HttpType.Get, object param = null, IDictionary <int, List <string> > replaceList = null, bool standardResult = true, int timeOut = 300000) where T1 : OperateResult <T2>, new() { HttpWebRequest request = null; HttpWebResponse response = null; StreamReader reader = null; Stream outStream = null; try { //构造http请求的对象 request = (HttpWebRequest)WebRequest.Create(url); //设置 request.ProtocolVersion = HttpVersion.Version11; request.Method = type.ToString().Replace("Form", "Post"); request.KeepAlive = false; request.Timeout = timeOut; var data = ""; if (param != null) { var name = param.GetType().Name; if (!("String,Int32,Int64").Contains(name)) { if (type.Equals(HttpType.Form)) { data = ObjectUtil.ToFormUrlEncoded(param); } else { data = JsonUtil.ToJson(param); } } else { data = param.ToString(); } } if (!string.IsNullOrEmpty(this.Token)) { request.Headers["Authorization"] = string.Format("Bearer {0}", this.Token); } if (Headers != null && Headers.Count > 0) { foreach (var h in this.Headers) { if (h.Value != null) { request.Headers[h.Key] = h.Value.ToString(); } } } if (data.Trim() != "") { if (type.Equals(HttpType.Form)) { request.ContentType = @"application/x-www-form-urlencoded"; } else { request.ContentType = @"application/json"; } request.MediaType = "application/json"; request.Accept = "application/json"; request.Headers["Accept-Language"] = "zh-CN,zh;q=0."; request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3"; //转成网络流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); request.ContentLength = buf.Length; outStream = request.GetRequestStream(); outStream.Flush(); outStream.Write(buf, 0, buf.Length); outStream.Flush(); outStream.Close(); } else if (type.Equals(HttpType.Post) || type.Equals(HttpType.Form) || type.Equals(HttpType.Put)) { request.ContentLength = 0; } // 获得接口返回值 response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); reader.Close(); response.Close(); request.Abort(); if (replaceList != null && replaceList.Count == 2) { for (var i = 0; i < replaceList[0].Count; i++) { content = content.Replace(replaceList[0][i], replaceList[1][i]); } } if (!standardResult) { content = string.Format("{{\"Data\":{0}, \"OperateStatus\":1}}", content); } var result = JsonUtil.FromJson <T1>(content); return(result); } catch (Exception ex) { if (outStream != null) { outStream.Close(); } if (reader != null) { reader.Close(); } if (response != null) { response.Close(); } if (request != null) { request.Abort(); } string error = ex.Message; var result = new T1() { OperateStatus = Common.Enums.OperateStatus.Failed, Message = error }; return(result); } }
/// <summary> /// Http Put请求。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri"></param> /// <param name="data"></param> /// <returns></returns> //public static T HttpPut<T>(string uri, object data) //{ // return HttpOper<T>(uri, data, HttpType.Put); //} /// <summary> /// Http Put请求。返回JSON字符串。 /// </summary> /// <param name="uri"></param> /// <param name="data"></param> /// <returns></returns> //public static string HttpPut(string uri, object data) //{ // return HttpOper(uri, data, HttpType.Put).ReadAsStringAsync().Result; //} /// <summary> /// Http Delete请求。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri"></param> /// <returns></returns> //public static T HttpDelete<T>(string uri) //{ // return HttpOper<T>(uri, null, HttpType.Delete); //} /// <summary> /// Http Delete请求。返回JSON字符串。 /// </summary> /// <param name="uri"></param> /// <param name="data"></param> /// <returns></returns> //public static string HttpDelete(string uri, object data) //{ // return HttpOper(uri, data, HttpType.Delete).ReadAsStringAsync().Result; //} /// <summary> /// Http各项操作。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri"></param> /// <param name="data"></param> /// <param name="type"></param> /// <returns></returns> //private static T HttpOper<T>(string uri, object data, HttpType type) //{ // var content = HttpOper(uri, data, type); // return content.ReadAsAsync<T>().Result; //} private static string HttpOper(string uri, object data, HttpType type) { if (uri == null) { throw new ArgumentNullException("uri"); } if (type == HttpType.Get && data != null) { if (!(data is Dictionary <string, string>)) { throw new NotSupportedException("HttpGet param must be Dictionary<string, string>"); } var param = (Dictionary <string, string>)data; var keyValues = param.Keys.Select(t => string.Format("{0}={1}", t, param[t])); var appendUri = string.Format("?{0}", string.Join("&", keyValues)); uri += appendUri; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = type.ToString("G").ToUpper(); request.ContentType = "application/json; charset=utf-8"; request.Timeout = 30 * 1000; if (type != HttpType.Get) { var dataString = data != null?data.ToJson() : ""; var dataArray = Encoding.UTF8.GetBytes(dataString); request.ContentLength = dataArray.Length; using (Stream sr = request.GetRequestStream()) { sr.Write(dataArray, 0, dataArray.Length); } } var response = (HttpWebResponse)request.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (StreamReader str = new StreamReader(stream, Encoding.UTF8)) { return(str.ReadToEnd()); } } //using (var client = new HttpClient()) //{ // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HttpResponseMessage response; // switch (type) // { // case HttpType.Get: // if (data != null) // { // if (!(data is Dictionary<string, string>)) // throw new NotSupportedException("HttpGet param must be Dictionary<string, string>"); // var param = (Dictionary<string, string>)data; // var keyValues = param.Keys.Select(t => string.Format("{0}={1}", t, param[t])); // var appendUri = string.Format("?{0}", string.Join("&", keyValues)); // uri += appendUri; // } // response = client.GetAsync(uri).Result; // break; // case HttpType.Post: // response = client.PostAsJsonAsync(uri, data).Result; // break; // case HttpType.Put: // response = client.PutAsJsonAsync(uri, data).Result; // break; // case HttpType.Delete: // response = client.DeleteAsync(uri).Result; // break; // default: // throw new ArgumentOutOfRangeException("type", type, null); // } // if (response.IsSuccessStatusCode) // return response.Content; // throw new HttpRequestException(response.StatusCode.ToString()); //} }