private static RequestMockResponse ConfigureRequestMockResponse( this RequestExpectation requestExpectation, HttpStatusCode responStatusCode, HttpRequestContentType responseContentType, object responseContent, IDictionary <string, string> responseHeaders, Func <HttpRequestMessage, HttpResponseMessage> responseBuilder) { requestExpectation.Response.ResponseStatusCode = responStatusCode; requestExpectation.Response.ResponseContentType = Helper.ParseResponseContentType(responseContentType); requestExpectation.Response.ResponseContent = responseContent; requestExpectation.Response.ResponseBuilder = responseBuilder; if (responseHeaders == null) { return(requestExpectation.Response); } foreach (var responseHeader in responseHeaders) { requestExpectation.Response.ResponseHeaders.Add(responseHeader.Key, responseHeader.Value); } return(requestExpectation.Response); }
private static RequestExpectation CreateHttpServerExpectation(HttpServerMock serverMock, HttpMethod requestMethod, string requetsUri, string name, uint times, HttpRequestContentType expectedContentType, object expectedRequestContent, IDictionary <string, string> expectedRequestHeaders, Func <HttpRequestMessage, bool> requestValidator) { var expectation = new RequestExpectation(requetsUri) { RequestHttpMethod = requestMethod, ExpectedRequestContent = expectedRequestContent, ExpectedRequestContentType = Helper.ParseRequestContentType(expectedContentType), Repeats = times, RequestValidator = requestValidator, Name = name }; if (expectedRequestHeaders != null) { foreach (var expectedRequestHeader in expectedRequestHeaders) { expectation.ExpectedRequestHeaders.Add(expectedRequestHeader.Key, expectedRequestHeader.Value); } } serverMock.ServerRequestsState.RequestExpectations.Add(expectation); return(expectation); }
private static string ConvertFromHContentTypeToString(HttpRequestContentType contentType) { switch (contentType) { case HttpRequestContentType.None: { return(string.Empty); } case HttpRequestContentType.Json: { return("application/json"); } case HttpRequestContentType.Xml: { return("application/xml"); } ////case HContentType.Text: //// { //// return "text/plain"; //// } ////case HContentType.FormUrlEncoded: //// { //// return "application/x-www-form-urlencoded"; //// } default: { throw new ArgumentOutOfRangeException("contentType"); } } }
/// <summary> /// Substitui corpo do método por chamada HTTP /// Corpo do método é chamada em caso de Exception, que pode ser obtida em HttpRequest.LastError /// </summary> /// <param name="url">Url em que será feita a chamada HTTP pode ser usado os coringas {nomeDoParametro} para substituição por parametro, @appSetting:NomeDaConfiguracao para substituição por configuração do AppSetting, @className e @methodName para substituição pelo nome da Classe e do Método</param> /// <param name="method">Método utilizado</param> /// <param name="responseType">Tipo de resposta</param> /// <param name="contentType">Tipo de conteudo enviado</param> public HttpRequest(string url, HttpRequestMethod method = HttpRequestMethod.GET, HttpRequestResponseType responseType = HttpRequestResponseType.JSON, HttpRequestContentType contentType = HttpRequestContentType.FormData) { Uri = url; Method = method; ResponseType = responseType; ContentType = contentType; Timeout = 120000; KeepAlive = true; }
internal static string ParseResponseContentType(HttpRequestContentType contentType) { switch (contentType) { case HttpRequestContentType.None: return(string.Empty); case HttpRequestContentType.Json: return("application/json"); case HttpRequestContentType.Xml: return("application/xml"); default: throw new ArgumentOutOfRangeException("contentType"); } }
internal static string ParseRequestContentType(HttpRequestContentType contentType) { switch (contentType) { case HttpRequestContentType.None: return(string.Empty); case HttpRequestContentType.Json: return(string.Join(",", JsonContentTypes)); case HttpRequestContentType.Xml: return(string.Join(",", XmlContentTypes)); default: throw new ArgumentOutOfRangeException("contentType"); } }
/// <summary> /// 获取请求头部 /// </summary> /// <param name="contentType">HttpRequestContentType.html</param> /// <returns></returns> private string GetContentType(HttpRequestContentType contentType) { string result = string.Empty; Type type = typeof(HttpRequestContentType); foreach (System.Reflection.MemberInfo mInfo in type.GetMembers()) { foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) { if (attr.GetType() == typeof(System.ComponentModel.DescriptionAttribute)) { if (mInfo.Name == contentType.ToString()) { result = ((System.ComponentModel.DescriptionAttribute)attr).Description; } } } } return(result); }
/// <summary> /// Responses the specified expectation. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expectation">The expectation.</param> /// <param name="responseStatusCode">The response status code.</param> /// <param name="responseContentType">Type of the response content.</param> /// <param name="responseContent">Content of the response.</param> /// <param name="responseHeaders">The response headers.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">expectation</exception> public static RequestMockResponse Response <T>( this RequestExpectation expectation, HttpStatusCode responseStatusCode, HttpRequestContentType responseContentType, T responseContent, IDictionary <string, string> responseHeaders = null) where T : class { if (expectation == null) { throw new ArgumentNullException("expectation"); } return(ConfigureRequestMockResponse( expectation, responseStatusCode, responseContentType, responseContent, responseHeaders, null)); }
/// <summary> /// Sets up get expectation. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serverMock">The server.</param> /// <param name="requetsUri">The requets URI.</param> /// <param name="times">The times.</param> /// <param name="name">The name.</param> /// <param name="expectedContentType">Expected type of the content.</param> /// <param name="expectedRequestContent">Expected content of the request.</param> /// <param name="expectedRequestHeaders">The expected request headers.</param> /// <param name="requestValidator">The request validator.</param> /// <returns></returns> public static RequestExpectation SetUpGetExpectation <T>( this HttpServerMock serverMock, string requetsUri, uint times = 1, string name = "", HttpRequestContentType expectedContentType = HttpRequestContentType.None, T expectedRequestContent = null, IDictionary <string, string> expectedRequestHeaders = null, Func <HttpRequestMessage, bool> requestValidator = null) where T : class { return(CreateHttpServerExpectation( serverMock, HttpMethod.GET, requetsUri, name, times, expectedContentType, expectedRequestContent, expectedRequestHeaders, requestValidator)); }
/// <summary> /// POST获取网址数据 /// </summary> /// <param name="url">请求网址</param> /// <param name="postData">发送内容</param> /// <param name="contentType">Content-Type 类型</param> /// <param name="codeType">编码 默认UTF-8</param> /// <returns></returns> public static string PostToUrl(string url, string postData, HttpRequestContentType contentType, string codeType = "utf-8") { HttpUtility.ContentType = contentType; return(HttpUtility.PostToUrl(url, postData, codeType)); }
private HttpContent CreateContentType(HttpRequestContentType? contentType, string bodyContent, string mimeType) { HttpContent content = null; if (contentType.HasValue && !string.IsNullOrEmpty(bodyContent)) { if (contentType == HttpRequestContentType.FormUrlEncodedContent) { var collection = HttpContentParser.ParseFormUrlEncodedContent(bodyContent); content = new FormUrlEncodedContent(collection); } else if (contentType == HttpRequestContentType.StringContent) { content = new StringContent(bodyContent, Encoding.UTF8, mimeType); } else { throw new NotImplementedException("Content type not yet implemented. Try FormUrlEncoded or StringContent"); } } return content; }
/// <summary> /// Adds a step to the load test plan. Each step is an HTTP request. /// </summary> /// <param name="headers">Collection of headers for this request</param> /// <param name="verb">The method to use</param> /// <param name="endpoint">The relative uri for the endpoint</param> /// <param name="contentType">The content-type of the request, if any</param> /// <param name="bodyContent">The content of the request, if any</param> /// <param name="mimeType">The mime type of the request, if any. Defaults to "application/json".</param> public Scenario AddStep(Dictionary<string, string> headers, string verb, string endpoint, HttpRequestContentType? contentType, string bodyContent, string mimeType = "application/json") { HttpMethod method = ParseMethod(verb); Uri uri = CreateUri(endpoint); HttpContent content = CreateContentType(contentType, bodyContent, mimeType); HttpRequestMessage step = new HttpRequestMessage(method, endpoint); if (headers != null && headers.Keys.Count > 0) { foreach (var key in headers.Keys) { step.Headers.Add(key, headers[key]); } } if (content != null) { step.Content = content; } this.Steps.Add(step); return this; }
public IEngine AddStep(Dictionary<string, string> headers, string verb, string endpoint, HttpRequestContentType? contentType, string bodyContent, string mimeType = "application/json") { this.scenario.AddStep(headers, verb, endpoint, contentType, bodyContent, mimeType); return this; }
/// <summary> /// Expecteds the type of the content. /// </summary> /// <param name="expectation">The expectation.</param> /// <param name="contentType">Type of the content.</param> /// <returns></returns> public static RequestExpectation ExpectedContentType(this RequestExpectation expectation, HttpRequestContentType contentType) { expectation.ExpectedRequestContentType = Helper.ParseRequestContentType(contentType); return(expectation); }
/// <summary> /// Expecteds the content. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expectation">The expectation.</param> /// <param name="content">The content.</param> /// <param name="contentType">Type of the content.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">expectation</exception> public static RequestExpectation ExpectedContent <T>(this RequestExpectation expectation, T content, HttpRequestContentType contentType) where T : class { if (expectation == null) { throw new ArgumentNullException("expectation"); } expectation.ExpectedRequestContent = content; expectation.ExpectedRequestContentType = Helper.ParseRequestContentType(contentType); return(expectation); }
/// <summary> /// 根据给定地址和请求类型获取内容 /// </summary> /// <param name="url">请求地址(可直接带参数)</param> /// <param name="method">请求方法</param> /// <param name="type">请求内容类型</param> /// <param name="content">请求内容(不需要就不传)</param> /// <returns></returns> public static string GetHttpResponse(string url, HttpRequestMethod method = HttpRequestMethod.GET, HttpRequestContentType type = HttpRequestContentType.Default, string content = null) { // 创建 WebRequest 对象,WebRequest 是抽象类,定义了规范 // HttpWebRequest 是 WebRequest 的派生类,专门用于 HTTP 请求 var request = (HttpWebRequest)HttpWebRequest.Create(url); // 请求的方式通过 Method 属性设置 ,默认为 GET // 可以将 Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。 switch (method) { case HttpRequestMethod.POST: request.Method = "POST"; break; case HttpRequestMethod.GET: default: request.Method = "GET"; break; } // 设置请求的内容类型 switch (type) { case HttpRequestContentType.UrlEncoded: request.ContentType = "application/x-www-form-urlencoded"; content = HttpContext.Current.Server.UrlEncode(content); break; case HttpRequestContentType.Json: request.ContentType = "application/json"; break; case HttpRequestContentType.Default: default: //request.ContentType = "text/plain"; break; } // 如果有请求内容的话,写入请求流中 if (!string.IsNullOrWhiteSpace(content)) { // 取得发向服务器的流 using (var requestStream = request.GetRequestStream()) { // 使用 POST 方法请求的时候,实际的参数通过请求的 Body 部分以流的形式传送 using (var writer = new StreamWriter(requestStream)) { writer.Write(content); } // 设置请求参数的长度. request.ContentLength = requestStream.Length; } } #region Cookies暂不需要 // 还可以在请求中附带 Cookie // 但是,必须首先创建 Cookie 容器 //request.CookieContainer = new CookieContainer(); //var requestCookie = new System.Net.Cookie("Request", "RequestValue", "/", "localhost"); //request.CookieContainer.Add(requestCookie); #endregion HttpWebResponse response; try { // GetResponse 方法才真的发送请求,等待服务器返回 response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; SignalRHelper.SendMessageToChatRoom("HTTP请求异常", response == null ? ex.Message : response.StatusDescription); } // 对请求结果的处理 if (response != null) { // 请求成功得到以流的形式表示的回应内容 using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { string result; //读取返回内容 using (var reader = new StreamReader(responseStream)) { result = reader.ReadToEnd(); } return result; } } } return string.Empty; }