• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# HttpMethod类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中HttpMethod的典型用法代码示例。如果您正苦于以下问题:C# HttpMethod类的具体用法?C# HttpMethod怎么用?C# HttpMethod使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HttpMethod类属于命名空间,在下文中一共展示了HttpMethod类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ProcessRequest

        private static async Task<RequestResponse> ProcessRequest(EasypayConfig config, string data, HttpMethod httpMethod, string path, string reqId)
        {
            var contentType = httpMethod.Method == "GET" ? "" : "application/vnd.ch.swisscom.easypay.direct.payment+json";
            var url = new Uri("https://" + config.Host + config.Basepath + path);
            var now = DateTime.Now;
            var date = now.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.GetCultureInfoByIetfLanguageTag("en")) + " +0000"; //Mon, 07 Dec 2015 09:01:30 +0000

            var client = new HttpClient();
            var request = new HttpRequestMessage(httpMethod, url);
            request.Headers.Add("X-SCS-Date", date);
            request.Headers.Add("X-Request-Id", reqId);
            request.Headers.Add("X-Merchant-Id", config.MerchantId);
            request.Headers.Add("X-CE-Client-Specification-Version", "1.1");

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.ch.swisscom.easypay.message.list+json"));
            request.Headers.Date = now;

            var md5Hash = data != null ? Signature.HashData(Encoding.UTF8.GetBytes(data)) : null;
            var hashString = Signature.CreateHashString(httpMethod.Method, md5Hash != null ? Convert.ToBase64String(md5Hash) : "", contentType, date, path);
            var signature = Signature.Sign(Encoding.UTF8.GetBytes(config.EasypaySecret), Encoding.UTF8.GetBytes(hashString));
            
            request.Headers.Add("X-SCS-Signature", Convert.ToBase64String(signature));

            if (data != null)
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                request.Content = new StringContent(data);
                request.Content.Headers.ContentMD5 = md5Hash;
            }

            var result = await client.SendAsync(request);
            var ret = new RequestResponse {Response = await result.Content.ReadAsStringAsync(), StatusCode = result.StatusCode};
            return ret;
        }
开发者ID:rolandschwarz,项目名称:easypay-signature-code,代码行数:34,代码来源:EasypayRequest.cs


示例2: Request

        public string Request(string url, HttpRequestParameter parameter, HttpMethod method, HttpHeader headers)
        {
            string _params = string.Empty;

            if (parameter != null && parameter.Count > 0)
            {
                _params = parameter.ToString();
            }

            if (method == HttpMethod.GET)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + _params;
                }
                else
                {
                    url = url + "?" + _params;
                }

                return HttpGet(url, headers);
            }
            else
            {
                return HttpPost(url, _params, headers);
            }
        }
开发者ID:revocengiz,项目名称:dot-net-sdk,代码行数:27,代码来源:HttpClient.cs


示例3: CreateTestMessage

 internal static HttpRequestMessage CreateTestMessage(string url, HttpMethod httpMethod, HttpConfiguration config)
 {
     HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod, url);
     IHttpRouteData rd = config.Routes[0].GetRouteData("/", requestMessage);
     requestMessage.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, rd);
     return requestMessage;
 }
开发者ID:OpenRIAServices,项目名称:OpenRiaServices,代码行数:7,代码来源:TestHelpers.cs


示例4: WebRequest

 /// <summary>
 /// Webs the request.
 /// </summary>
 /// <param name="method">The method.</param>
 /// <param name="url">The URL.</param>
 /// <param name="postData">The post data.</param>
 /// <returns></returns>
 public string WebRequest(HttpMethod method, string url, string postData)
 {
     this.Message = string.Empty;
     HttpWebRequest webRequest = null;
     StreamWriter requestWriter = null;
     string responseData = "";
     webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
     webRequest.Method = method.ToString();
     webRequest.ServicePoint.Expect100Continue = false;
     if (method == HttpMethod.POST)
     {
         webRequest.ContentType = "application/x-www-form-urlencoded";
         requestWriter = new StreamWriter(webRequest.GetRequestStream());
         try
         {
             requestWriter.Write(postData);
         }
         catch (Exception ex)
         {
             this.Message = ex.Message;
         }
         finally
         {
             requestWriter.Close();
             requestWriter = null;
         }
     }
     responseData = GetWebResponse(webRequest);
     webRequest = null;
     return responseData;
 }
开发者ID:JPomichael,项目名称:IPOW,代码行数:38,代码来源:WebHttpHelper.cs


示例5: RequestData

		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = global.HttpPipeliningEnabled || (local?.EnableHttpPipelining).GetValueOrDefault(false);
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Headers = global.Headers;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout = 
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.CancellationToken = local?.CancellationToken ?? CancellationToken.None;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
开发者ID:jeroenheijmans,项目名称:elasticsearch-net,代码行数:30,代码来源:RequestData.cs


示例6: HasApiRoute

        /// <summary>
        /// Asserts that the API route exists, has the specified Http method and meets the expectations
        /// </summary>
        public static void HasApiRoute(HttpConfiguration config, string url, HttpMethod httpMethod, object expectations)
        {
            var propertyReader = new PropertyReader();
            var expectedProps = propertyReader.Properties(expectations);

            HasApiRoute(config, url, httpMethod, expectedProps);
        }
开发者ID:segilbert,项目名称:MvcRouteTester,代码行数:10,代码来源:RouteAssert.cs


示例7: MockHttpRequest

 public MockHttpRequest(HttpMethod method, string relativeUrl, NameValueCollection queryParams, string requestBody)
 {
     this.method = method;
     this.relativeUrl = relativeUrl;
     this.queryParams = queryParams;
     this.requestBody = requestBody ?? string.Empty;
 }
开发者ID:jaredrussell,项目名称:MvcRouteTester,代码行数:7,代码来源:MockHttpRequest.cs


示例8: Create

        public ITwitterQuery Create(string queryURL, HttpMethod httpMethod)
        {
            var queryURLParameter = new ConstructorNamedParameter("queryURL", queryURL);
            var httpMethodParameter = new ConstructorNamedParameter("httpMethod", httpMethod);

            return _twitterQueryFactory.Create(queryURLParameter, httpMethodParameter);
        }
开发者ID:Murtaza-libs,项目名称:tweetinvi,代码行数:7,代码来源:TwitterQueryFactory.cs


示例9: WebJob

 protected WebJob()
 {
     Method = HttpMethod.Get;
     formData = new List<KeyValuePair<string, string>>();
     headers = new List<KeyValuePair<string, string>>();
     formString = null;
 }
开发者ID:KRSogaard,项目名称:JobScrapingFramework,代码行数:7,代码来源:WebJob.cs


示例10: SendODataHttpRequestWithCanary

        public static async Task<byte[]> SendODataHttpRequestWithCanary(Uri uri, HttpMethod method, Stream requestContent, string contentType,
            HttpClientHandler clientHandler, SPOAuthUtility authUtility, Dictionary<string, string> headers = null)
        {
            // Make a post request to {siteUri}/_api/contextinfo to get the canary
            var response = await HttpUtility.SendODataJsonRequest(
                new Uri(String.Format("{0}/_api/contextinfo", SPOAuthUtility.Current.SiteUrl)),
                HttpMethod.Post,
                null,
                clientHandler,
                SPOAuthUtility.Current);

            Dictionary<String, IJsonValue> dict = new Dictionary<string, IJsonValue>();
            HttpUtility.ParseJson(JsonObject.Parse(Encoding.UTF8.GetString(response, 0, response.Length)), dict);

            string canary = dict["FormDigestValue"].GetString();

            // Make the OData request passing the canary in the request headers
            return await HttpUtility.SendODataHttpRequest(
                uri,
                method,
                requestContent,
                contentType,
                clientHandler,
                SPOAuthUtility.Current,
                new Dictionary<string, string> { 
                { "X-RequestDigest", canary  } 
                });
        }
开发者ID:paraneye,项目名称:WinApp,代码行数:28,代码来源:HttpUtility.cs


示例11: Stream

        public override Response Stream(Uri url, HttpMethod method, Func<HttpWebResponse, bool, Response> responseBuilderCallback, Stream contents, int bufferSize, long maxReadLength, Dictionary<string, string> headers, Dictionary<string, string> queryStringParameters, RequestSettings settings, Action<long> progressUpdated)
        {
            if (settings == null)
                settings = new JsonRequestSettings();

            return base.Stream(url, method, responseBuilderCallback, contents, bufferSize, maxReadLength, headers, queryStringParameters, settings, progressUpdated);
        }
开发者ID:bretmcg,项目名称:SimpleRestServices,代码行数:7,代码来源:JsonRestService.cs


示例12: Execute

        public override Response Execute(Uri url, HttpMethod method, Func<HttpWebResponse, bool, Response> responseBuilderCallback, string body, Dictionary<string, string> headers, Dictionary<string, string> queryStringParameters, RequestSettings settings)
        {
            if (settings == null)
                settings = new JsonRequestSettings();

            return base.Execute(url, method, responseBuilderCallback, body, headers, queryStringParameters, settings);
        }
开发者ID:bretmcg,项目名称:SimpleRestServices,代码行数:7,代码来源:JsonRestService.cs


示例13: Request

 private Request(string url, HttpMethod httpMethod, string entity = null)
 {
     _url = url;
     _httpMethod = httpMethod;
     _entity = entity;
     _webRequest = CreateWebRequest(_url, _entity, _httpMethod);
 }
开发者ID:bnathyuw,项目名称:nonae,代码行数:7,代码来源:Request.cs


示例14: Add

 public static BatchStep Add(this IList<BatchStep> list, HttpMethod method, string to, object body)
 {
     var id = list.Count;
     var step = new BatchStep {Method = method, To = to, Body = body, Id = id};
     list.Add(step);
     return step;
 }
开发者ID:Readify,项目名称:Neo4jClient,代码行数:7,代码来源:BatchStepExtensions.cs


示例15: CallAzureMLSM

        private async Task<string> CallAzureMLSM(HttpMethod method, string url, string payload)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessContext.WorkspaceAccessToken);

                HttpRequestMessage req = new HttpRequestMessage(method, url);

                if (!string.IsNullOrWhiteSpace(payload))
                {
                    req.Content = new StringContent(payload);
                    req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }

                HttpResponseMessage response = await client.SendAsync(req);
                string result = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return result;
                }
                else
                {
                    throw new HttpRequestException(string.Format("{0}\n{1}", result, response.StatusCode));
                }
            }
        }
开发者ID:abhi1509,项目名称:RRSWarmer,代码行数:27,代码来源:ServiceManagerCaller.cs


示例16: CreateJsonRequest

        private static HttpRequestMessage CreateJsonRequest(string url, HttpMethod method)
        {
            var request = new HttpRequestMessage(method, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return request;
        }
开发者ID:jkonecki,项目名称:esvstools,代码行数:7,代码来源:SimpleHttpClient.cs


示例17: HttpWorker

        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
开发者ID:evest,项目名称:Netling,代码行数:35,代码来源:HttpWorker.cs


示例18: OAuthGenerator

 /// <summary>
 /// Default Constructor
 /// </summary>
 /// <param name="consumerKey"></param>
 /// <param name="consumerSecret"></param>        
 public OAuthGenerator(string consumerKey, string consumerSecret)
 {
     this.queryParameters = new ArrayList();
     this.consumerKey = consumerKey;
     this.consumerSecret = System.Text.Encoding.ASCII.GetBytes(consumerSecret);
     this.methodHttp = HttpMethod.POST;
 }
开发者ID:nayosx,项目名称:sdk-core-dotnet,代码行数:12,代码来源:OAuthGenerator.cs


示例19: MakeHttpRequest

 public WebRequest MakeHttpRequest(Uri request, HttpMethod httpMethod)
 {
     return this.consumer.CreateHttpRequest(
         request.AbsoluteUri,
         httpMethod,
         new UriBuilder(request).GetQueryParams().ToArray());
 }
开发者ID:drewzif84,项目名称:OAuthClient,代码行数:7,代码来源:OAuth1aClientConsumerAdapter.cs


示例20: HandleError

    	/// <summary>
        /// Handles the error in the given response. 
        /// <para/>
        /// This method is only called when HasError() method has returned <see langword="true"/>.
        /// </summary>
        /// <remarks>
        /// This implementation throws appropriate exception if the response status code 
        /// is a client code error (4xx) or a server code error (5xx). 
        /// </remarks>
        /// <param name="requestUri">The request URI.</param>
        /// <param name="requestMethod">The request method.</param>
        /// <param name="response">The response message with the error.</param>
        public override void HandleError(Uri requestUri, HttpMethod requestMethod, HttpResponseMessage<byte[]> response)
        {
			if (response == null) throw new ArgumentNullException("response");

            var type = (int)response.StatusCode / 100;
            switch (type)
            {
            	case 4:
            		HandleClientErrors(response);
            		break;
            	case 5:
            		HandleServerErrors(response.StatusCode);
            		break;
            }

            // if not otherwise handled, do default handling and wrap with StackExchangeApiException
            try
            {
                base.HandleError(requestUri, requestMethod, response);
            }
            catch (Exception ex)
            {
                throw new StackExchangeApiException("Error consuming StackExchange REST API.", ex);
            }
        }
开发者ID:scottksmith95,项目名称:CSharp.StackExchange,代码行数:37,代码来源:StackExchangeErrorHandler.cs



注:本文中的HttpMethod类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# HttpNotificationChannel类代码示例发布时间:2022-05-24
下一篇:
C# HttpMessageHandlerMock类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap