async Task <HttpResponseMessage> GetHttpMethod(string url, HttpMethodType method) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders .Accept .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(mediaType)); switch (method) { case HttpMethodType.POST: return(await client.PostAsync(url, new StringContent(data))); case HttpMethodType.GET: return(await client.GetAsync(url)); case HttpMethodType.DELETE: return(await client.DeleteAsync(url)); case HttpMethodType.PUT: return(await client.PutAsync(url, new StringContent(data))); default: throw new System.Exception("This http method doesn't exist or isn't currently supported."); } }
public Link(LinkType type, string rel, string href, HttpMethodType method) { this.type = type.ToString(); this.rel = rel.ToString(); this.href = href; this.method = method.ToString(); }
public Mock Find(string path, HttpMethodType verb) { using (var session = dataContext.OpenSession()) { var sanitisedPath = StripParams(path); var pathEq = Query.EQ(Path, sanitisedPath); var verbEq = Query.EQ(Verb, verb.ToString()); var query = Query.And(pathEq, verbEq); var mock = session.Mocks.FindOne(query); /*if (mock == null) { var routeMatch = Query.And(Query.Contains(Path, "{"), Query.Contains(Path, "}")); var routes = session.Mocks.Find(Query.And(routeMatch, Query.EQ(Verb, verb.ToString()))).ToList(); var fuzzyMock = (from route in routes where route.Path.Split('/').Length == path.Split('/').Length let co = route.Path.DiceCoefficient(path) where co > .4d orderby co descending select new {Match = route, Coefficient = co}).ToList(); Trying commenting this out - is fuzzy-match a key feature? mock = fuzzyMock.FirstOrDefault()?.Match; }*/ return mock; } }
private async Task <Response> Execute(string url, HttpMethodType method, string body = "") { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue(mediaType)); using (HttpResponseMessage res = await GetHttpMethod(url, method, body)) { using (HttpContent content = res.Content) { string data = await content.ReadAsStringAsync(); Response response = new Response(); response.body = data; HttpHeaders h = content.Headers; foreach (var header in h) { response.headers.Add(header.Key, header.Value); } return(response); } } }
public string GetMethodTypeName(HttpMethodType methodType) { switch (methodType) { case HttpMethodType.UNKNOWN: return("UNKNOWN"); case HttpMethodType.DELETE: return("DELETE"); case HttpMethodType.GET: return("GET"); case HttpMethodType.HEAD: return("HEAD"); case HttpMethodType.MERGE: return("MERGE"); case HttpMethodType.OPTIONS: return("OPTIONS"); case HttpMethodType.PATCH: return("PATCH"); case HttpMethodType.POST: return("POST"); case HttpMethodType.PUT: return("PUT"); default: throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null); } }
private async Task <HttpResponseMessage> GetHttpMethod(string url, HttpMethodType method, string body = "") { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue(mediaType)); switch (method) { case HttpMethodType.POST: return(await client.PostAsync(url, new StringContent(body))); case HttpMethodType.GET: return(await client.GetAsync(url)); case HttpMethodType.DELETE: return(await client.DeleteAsync(url)); case HttpMethodType.PUT: return(await client.PutAsync(url, new StringContent(body))); default: throw new Exception("This http method doesn't exist or it's currently not supported"); } }
//public Image GetImage() //{ // Process(HttpMethodType.GET); // return GetImageFromResponse(); //} //public Image PostImage() //{ // Process(HttpMethodType.POST); // return GetImageFromResponse(); //} public void GetFileFromResponse(HttpMethodType method, string path, string filename) { if (string.IsNullOrEmpty(filename)) { if (Response.Headers["Content-Disposition"] != null) { filename = Regex.Match(Response.Headers["Content-Disposition"], @"filename=(\S+)").Groups[1].Value; } else { filename = Guid.NewGuid().ToString(); } } using (Response) { using (Stream stream = Response.GetResponseStream()) { using (FileStream fileStream = File.Create(path + filename)) { //建立字节组,并设置它的大小是多少字节 byte[] bytes = new byte[102400]; int n = 1; while (n > 0) { //一次从流中读多少字节,并把值赋给N,当读完后,N为0,并退出循环 n = stream.Read(bytes, 0, 10240); fileStream.Write(bytes, 0, n); //将指定字节的流信息写入文件流中 } } } } }
public async Task <HttpResponseMessage> SendRequestAsync(HttpMethodType method, string url, Sale sale = null) { switch (method) { case HttpMethodType.GET: return(await _httpClient.GetAsync(url)); case HttpMethodType.POST: var jsonPost = JsonConvert.SerializeObject(sale, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); var contentPost = new StringContent(jsonPost, Encoding.UTF8, "application/json"); return(await _httpClient.PostAsync(url, contentPost)); case HttpMethodType.PUT: var json = JsonConvert.SerializeObject(sale, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); var content = new StringContent(json, Encoding.UTF8, "application/json"); return(await _httpClient.PutAsync(url, content)); default: //_httpClient.SendAsync() break; } return(null); }
public RequestParameters(string baseUrl, string apiUrl, HttpMethodType type) { this.BaseUrl = baseUrl; this.ApiUrl = apiUrl; this.Method = type; SetDefaultValue(); }
/// <summary> /// 自动补全请求 /// </summary> /// <param name="type"></param> /// <param name="methodOrUri"></param> /// <param name="request"></param> /// <returns></returns> protected static string richRequest(HttpMethodType type, string methodOrUri, YopRequest request) { Assert.notNull(methodOrUri, "method name or rest uri"); if (methodOrUri.StartsWith(request.getServerRoot()))//检查是否以指定字符开头 { methodOrUri = methodOrUri.Substring(request.getServerRoot().Length); } bool isRest = methodOrUri.StartsWith("/rest/"); //检查是否以指定字符开头 request.setRest(isRest); //临时变量,避免多次判断 string serverUrl = request.getServerRoot(); if (isRest) { methodOrUri = mergeTplUri(methodOrUri, request); serverUrl += methodOrUri; string version = Regex.Match(methodOrUri, "(?<=/rest/v).*?(?=/)").Value; if (StringUtils.isNotBlank(version)) { request.setVersion(version); } } else { serverUrl += "/command?" + YopConstants.METHOD + "=" + methodOrUri; } request.setMethod(methodOrUri); return(serverUrl); }
public Submit Process(HttpMethodType method) { SetRequest(method); SetResponse(); SetNewUrl(); return(this); }
public Mock Find(string path, HttpMethodType verb) { using (var session = dataContext.OpenSession()) { var pathEq = Query.EQ(Path, path); var verbEq = Query.EQ(Verb, verb.ToString()); var query = Query.And(pathEq, verbEq); var mock = session.Mocks.FindOne(query); if (mock == null) { var routeMatch = Query.And(Query.Contains(Path, "{"), Query.Contains(Path, "}")); var routes = session.Mocks.Find(Query.And(routeMatch, Query.EQ(Verb, verb.ToString()))).ToList(); var fuzzyMock = (from route in routes let co = route.Path.DiceCoefficient(path) orderby co descending select route).FirstOrDefault(); if (fuzzyMock == null) { return null; } mock = fuzzyMock; } return mock; } }
public static Tuple <Condition, string> SendPost(HttpMethodType type, string url, JObject jObject) { try { WebRequest request = WebRequest.Create(url); request.Timeout = 3000; request.Method = type.ToString(); request.ContentType = "application/json; charset=utf-8"; request.Headers.Add("authorization", "token apikey"); byte[] buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jObject, Formatting.Indented)); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); using StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8); return(new Tuple <Condition, string>(Condition.Success, reader.ReadToEnd())); } catch (Exception e) { return(new Tuple <Condition, string>(Condition.Error, e.Message)); } }
internal string CreateCanonicalRequest(Guid requestId, string url, HttpMethodType method, IReadOnlyDictionary <string, string> headers, IReadOnlyDictionary <string, string> query, string contentHash) { _logger.LogTrace("Creating canonical request for {RequestId}", requestId); //Consists of: // HTTP Verb + \n // Canonical URI + \n // Canonical Query String + \n // Canonical Headers + \n // Signed Headers + \n // Sha256 Content Hash StringBuilder sb = StringBuilderPool.Shared.Rent(300); sb.Append(method.ToString()).Append(SigningConstants.Newline); sb.Append(url).Append(SigningConstants.Newline); sb.Append(CanonicalizeQueryParameters(query)).Append(SigningConstants.Newline); //Headers needs to be ordered by key OrderedDictionary <string, string> orderedHeaders = new OrderedDictionary <string, string>(HeaderWhitelist.FilterHeaders(headers)); sb.Append(CanonicalizeHeaders(orderedHeaders)).Append(SigningConstants.Newline); sb.Append(CanonicalizeHeaderNames(orderedHeaders)).Append(SigningConstants.Newline); sb.Append(contentHash); string canonicalRequest = StringBuilderPool.Shared.ReturnString(sb); _logger.LogDebug("CanonicalRequest: {CanonicalRequest}", canonicalRequest); return(canonicalRequest); }
// /{controller}/{action}/ private static void AutoRegisterActionRoutes(IList <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection) { var controllers = application.GetType() .Assembly .GetTypes() .Where(type => type.IsSubclassOf(typeof(Controller)) && !type.IsAbstract); foreach (Type controller in controllers) { var actions = controller.GetMethods().Where(x => !x.IsSpecialName && !x.IsConstructor && x.IsPublic && x.DeclaringType == controller); foreach (var action in actions) { string url = "/" + controller.Name.Replace("Controller", string.Empty) + "/" + action.Name; HttpMethodAttribute attribute = action.GetCustomAttributes() .FirstOrDefault(x => x.GetType() .IsSubclassOf(typeof(HttpMethodAttribute))) as HttpMethodAttribute; HttpMethodType httpActionType = HttpMethodType.Get; if (attribute != null) { httpActionType = attribute.Type; if (attribute.Url != null) { url = attribute.Url; } } routeTable.Add(new Route(httpActionType, url, (request) => InvokeAction(request, serviceCollection, controller, action))); } } }
internal RestRequest(HttpMethodType methodType, string url, string path, string messageBody) { MethodType = methodType; RawUrl = url; Path = path; MessageBody = messageBody; }
public void TestCtor(string url, HttpMethodType method) { var req = new HttpReq(url, method); req.Host("localhost"); var realUrl = req.GetUrl(); }
public Promise(string mediaType, string url, string data, HttpMethodType method) { this.url = url; this.data = data; this.method = method; this.mediaType = mediaType; }
/// <summary> /// 验证url /// </summary> /// <returns></returns> public static bool JudgeByUrl(HttpControllerContext context) { bool res = true; HttpMethodType method = (HttpMethodType)Enum.Parse(typeof(HttpMethodType), context.Request.Method.ToString()); switch (method) { #region get方式 case HttpMethodType.GET: res = JudgeSqlInjectionByGetMethod(context); break; #endregion #region post方式 case HttpMethodType.POST: res = JudgeSqlInjectionByPostMethod(context); break; #endregion #region 其他方式 default: break; #endregion } return(res); }
public string Request(HttpMethodType httpMethod, string resourcePath, WebHeaderCollection requestHeaders, byte[] requestBody) { WebResponse response = this.CurrentConsumer.Request(httpMethod, resourcePath, this, requestHeaders, requestBody); var streamReader = new StreamReader(response.GetResponseStream()); var responseBody = streamReader.ReadToEnd(); return responseBody; }
/// <summary> /// 发送请求 /// </summary> /// <param name="url">url地址</param> /// <param name="type"></param> /// <param name="data">参数字典</param> /// <param name="heads">heads</param> /// <param name="encoding">字符集</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="MateralHttpException"></exception> private static async Task <string> SendAsync(string url, HttpMethodType type, object data, Dictionary <string, string> heads, Encoding encoding) { byte[] resultBytes = await SendByteAsync(url, type, data, heads); string result = encoding.GetString(resultBytes); return(result); }
public MockResponse FindActiveResponse(string path, HttpMethodType verb) { var mock = Find(path, verb); var activeStatus = mock?.ActiveStatusCode; return mock?.Responses.FirstOrDefault(x => x.StatusCode == activeStatus); }
private void SetHttpRequest(HttpMethodType method, Action <WebRequestParamHelper> action = null) { _Param.SetHttpMethod(method); if (action != null) { action(_Param); } }
public string Request(HttpMethodType httpMethod, string resourcePath, WebHeaderCollection requestHeaders, byte[] requestBody) { WebResponse response = this.CurrentConsumer.Request(httpMethod, resourcePath, this, requestHeaders, requestBody); var streamReader = new StreamReader(response.GetResponseStream()); var responseBody = streamReader.ReadToEnd(); return(responseBody); }
internal HttpRequestData(HttpMethodType methodType, string url, string path, HttpListenerContext context, string messageBody) { MethodType = methodType; RawUrl = url; Path = path; Context = context; MessageBody = messageBody; ContentEncoding = context.Request.ContentEncoding; }
public Link(LinkType type, Enum rel, string href, HttpMethodType method) : this( type : type, rel : rel.ToString(), href : href, method : method ) { }
/// <inheritdoc/> public void AddTableToLogger(string connectorName, string tableName, HttpMethodType httpMethod) { AddApiRequest(new LoggingApiContextValues { ConnectorName = connectorName, ResourceName = tableName, ResourceType = "table", HttpMethod = httpMethod.ToString() }, _timeProvider.UtcNow); }
internal void SetPostResponseModel(HttpMethodType type) { ResponseModel = new PostResponseModel { ModelValidation = new ModelValidationOutput { IsValid = true } }; MethodType = type; }
public override string MakeRequest(string uri, ResponseFormatType responseFormat, HttpMethodType httpMethodType, byte[] body, bool rawBody, bool isPhoto) { var rawResponse = string.Empty; if (this.AccessToken == null && string.IsNullOrEmpty(this.OAuthTokenKey) && string.IsNullOrEmpty(this.OAuthTokenSecret)) { throw new QzoneException("Can not make a request to a Protected Resource without a valid OAuth Access Token Key and Secret", QzoneExceptionType.TOKEN_REQUIRED); } if (this.AccessToken == null) { this.AccessToken = new AccessToken(this.OAuthConsumer, this.OAuthTokenKey, this.OAuthTokenSecret, this.OpenId); } this.OAuthConsumer.ResponseType = responseFormat; this.OAuthConsumer.Scheme = AuthorizationSchemeType.QueryString; switch (httpMethodType) { case HttpMethodType.POST: if (rawBody) { this.OAuthConsumer.ResponsePost(uri, body, rawBody, this.AccessToken.TokenKey, this.AccessToken.TokenSecret, this.AccessToken.Openid, isPhoto); } else { this.OAuthConsumer.ResponsePost(uri, body, this.AccessToken.TokenKey, this.AccessToken.TokenSecret, this.AccessToken.Openid); } break; case HttpMethodType.GET: this.OAuthConsumer.ResponseGet(uri, this.AccessToken.TokenKey, this.AccessToken.TokenSecret, this.AccessToken.Openid); break; default: break; } var httpResponse = this.OAuthConsumer.GetResponse() as HttpWebResponse; if (httpResponse != null) { var statusCode = (int)httpResponse.StatusCode; var streamReader = new StreamReader(httpResponse.GetResponseStream()); var responseBody = streamReader.ReadToEnd(); if (statusCode != 200 && statusCode != 201) { throw new QzoneException(string.Format("Your request received a response with status code {0}. {1}", statusCode, responseBody), QzoneExceptionType.REQUEST_FAILED, responseBody); } return(responseBody); } else { throw new QzoneException("Error making request.", QzoneExceptionType.REMOTE_ERROR); } }
/// <inheritdoc /> public HttpMethod GetMethod(HttpMethodType type) { try { return(KnownMethods[type]); } catch (KeyNotFoundException) { throw new UnknownHttpMethodException($"Unknown HTTP method: {type}."); } }
/// <summary> /// 发送请求 /// </summary> /// <param name="url">url地址</param> /// <param name="type"></param> /// <param name="data">参数字典</param> /// <param name="heads">heads</param> /// <param name="encoding">字符集</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="MateralHttpException"></exception> private static string Send(string url, HttpMethodType type = HttpMethodType.Get, object data = null, Dictionary <string, string> heads = null, Encoding encoding = null) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] resultBytes = SendBytes(url, type, data, heads); string result = encoding.GetString(resultBytes); return(result); }
/// <inheritdoc/> public void AddTableToLogger(string connectorName, string tableName, HttpMethodType httpMethod, object[] primaryKey) { AddApiRequest(new LoggingApiContextValues { ConnectorName = connectorName, ResourceName = tableName, ResourceType = "table", HttpMethod = httpMethod.ToString(), ResourceId = string.Join(";", primaryKey?.Select(c => c.ToString()) ?? new List <string>()) }, _timeProvider.UtcNow); }
public Stream DownloadMp3Stream(HttpMethodType method) { using (Response) { if (Response.Headers["Content-Type"] == "audio/mp3") { return(Response.GetResponseStream()); } } return(null); }
public WebResponse RawRequest(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody) { if (string.IsNullOrEmpty(resourcePath)) { throw new ArgumentNullException("resourcePath"); } var request = (HttpWebRequest)WebRequest.Create(this.ApiServerUri + resourcePath); request.Method = httpMethod.ToString(); return(RawRequest(request, requestHeaders, requestBody)); }
public WebResponse Request(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody, bool rawBody, CookieCollection cookieCollection, bool isPhoto) { var signer = new OAuthSigner(); var additionalParameters = new NameValueCollection(); WebRequest request = null; request = WebRequest.Create(this.ApiServerUri + resourcePath); if (httpMethod != HttpMethodType.GET) { if (rawBody) { if (isPhoto) { request.ContentType = "image/jpg"; } else { request.ContentType = "video/mpeg"; // f0r AVI video } } else { if (this.Scheme == AuthorizationSchemeType.Body) { request.ContentType = "application/" + OAuthConstants.X_WWW_FORM_URLENCODED; } else { request.ContentType = "application/" + OAuthConstants.X_WWW_FORM_URLENCODED; } if (requestBody != null && requestBody.Length > 0) { additionalParameters = HttpUtility.ParseQueryString(Encoding.UTF8.GetString(requestBody)); } } } request.Method = httpMethod.ToString(); string oAuthQuerystring = null; request = signer.SignRequest(request, this, consumerToken, additionalParameters, out oAuthQuerystring); ((HttpWebRequest)request).Accept = "*/*"; if (httpMethod == HttpMethodType.POST && !isPhoto && !string.IsNullOrEmpty(oAuthQuerystring)) { requestBody = Encoding.ASCII.GetBytes(oAuthQuerystring); } return(RawRequest(request, requestHeaders, requestBody, cookieCollection)); }
public HttpRequestItem(string rawUrl, HttpMethodType method) { RawUrl = rawUrl; Method = method; HeaderMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [HttpConstants.ContentType] = Method == HttpMethodType.Post ? HttpConstants.DefaultPostContentType : HttpConstants.DefaultGetContentType, }; ValueMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); EncodingType = Encoding.UTF8; }
private HttpWebRequest CreateRequest( string url, HttpMethodType methodType = HttpMethodType.Get ) { var request = (HttpWebRequest)WebRequest.Create( url ); request.Accept = "application/json"; request.Method = methodType.ToString().ToUpper(); request.Credentials = new CredentialCache { { new Uri(BASE_URL), AuthenticationType.Basic.ToString(), new NetworkCredential(_apiKeyId, _apiKeySecret) } }; return request; }
public HttpRequestItem(HttpMethodType method, string rawUrl) { Uri = new Uri(rawUrl); // RawUrl = rawUrl; Method = method; HeaderMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [HttpConstants.ContentType] = Method == HttpMethodType.Post ? HttpConstants.DefaultPostContentType : HttpConstants.DefaultGetContentType, [HttpConstants.Host] = Uri.Host, }; if (Method != HttpMethodType.Get) { HeaderMap[HttpConstants.ContentType] = HttpConstants.DefaultPostContentType; } _rawData = new StringBuilder(); EncodingType = Encoding.UTF8; }
/// <summary> /// Authorizationヘッダを作成します。 /// </summary> /// <param name="uri">リクエストURI</param> /// <param name="realm">保護領域</param> /// <param name="query">パラメータ</param> /// <param name="token">OAuthトークン</param> /// <param name="verifier">OAuth Verifier</param> /// <param name="callback">コールバック</param> /// <param name="methodType">HTTPメソッド</param> /// <returns>作成されたヘッダ</returns> public static string CreateAuthorizationHeader(Uri uri, string realm, IEnumerable<KeyValuePair<string, string>> query, Token token, string verifier, string callback, HttpMethodType methodType) { var oauthHeaders = GenerateOAuthParameter(token, null, null); oauthHeaders.Add("oauth_signature", GenerateSignature(uri, query != null ? query.Concat(oauthHeaders) : oauthHeaders, token, verifier, callback, methodType)); if (!string.IsNullOrEmpty(realm)) oauthHeaders.Add("realm", realm); return "OAuth " + string.Join(",", oauthHeaders.Select(kvp => string.Format(@"{0}=""{1}""", kvp.Key, UrlEncode(kvp.Value)))); }
public WebResponse RawRequest(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody) { if (string.IsNullOrEmpty(resourcePath)) { throw new ArgumentNullException("resourcePath"); } var request = (HttpWebRequest)WebRequest.Create(this.ApiServerUri + resourcePath); request.Method = httpMethod.ToString(); return RawRequest(request, requestHeaders, requestBody); }
public WebResponse Request(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken) { return Request(httpMethod, resourcePath, consumerToken, null, null, null); }
public WebResponse Request(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody) { return Request(httpMethod, resourcePath, consumerToken, requestHeaders, requestBody, null); }
public WebResponse Request(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody, bool rawBody, CookieCollection cookieCollection) { return Request(httpMethod, resourcePath, consumerToken, requestHeaders, requestBody, false, cookieCollection, false); }
public WebResponse Request(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders, byte[] requestBody, bool rawBody, CookieCollection cookieCollection, bool isPhoto) { var signer = new OAuthSigner(); var additionalParameters = new NameValueCollection(); WebRequest request = null; request = WebRequest.Create(this.ApiServerUri + resourcePath); if (httpMethod != HttpMethodType.GET) { if (rawBody) { if (isPhoto) request.ContentType = "image/jpg"; else request.ContentType = "video/mpeg"; // f0r AVI video } else { if (this.Scheme == AuthorizationSchemeType.Body) { request.ContentType = "application/" + OAuthConstants.X_WWW_FORM_URLENCODED; } else { request.ContentType = "application/" + OAuthConstants.X_WWW_FORM_URLENCODED; } if (requestBody != null && requestBody.Length > 0) { additionalParameters = HttpUtility.ParseQueryString(Encoding.UTF8.GetString(requestBody)); } } } request.Method = httpMethod.ToString(); string oAuthQuerystring = null; request = signer.SignRequest(request, this, consumerToken, additionalParameters,out oAuthQuerystring); ((HttpWebRequest)request).Accept = "*/*"; if (httpMethod == HttpMethodType.POST && !isPhoto && !string.IsNullOrEmpty(oAuthQuerystring)) { requestBody = Encoding.ASCII.GetBytes(oAuthQuerystring); } return RawRequest(request, requestHeaders, requestBody, cookieCollection); }
public OAuthToken TokenRequest(HttpMethodType httpMethod, string resourcePath) { return this.TokenRequest(httpMethod, resourcePath, new ConsumerToken(this, string.Empty, string.Empty), new WebHeaderCollection()); }
/// <summary> /// oauth_signatureの作成 /// </summary> /// <param name="uri">リクエストURI</param> /// <param name="query">OAuth関連ヘッダとパラメータ</param> /// <param name="token">OAuthトークン</param> /// <param name="verifier">OAuth Verifier</param> /// <param name="callback">コールバック</param> /// <param name="methodType">HTTPメソッド</param> /// <returns>作成されたoauth_signature</returns> public static string GenerateSignature(Uri uri, IEnumerable<KeyValuePair<string, string>> query, Token token, string verifier, string callback, HttpMethodType methodType) { //文字列作成 var param = string.Join("&", query.OrderBy(kvp => kvp.Key)//ここまずいかも .Select(kvp => string.Format("{0}={1}", UrlEncode(kvp.Key), UrlEncode(kvp.Value)))); var signatureBase = string.Format("{0}&{1}&{2}", methodType.ToString(), UrlEncode(string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath)), UrlEncode(param)); //ハッシュ生成 var key = string.Format("{0}&{1}", token.ConsumerSecret, token.OAuthTokenSecret); using (var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key))) { return Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase))); } }
private void InitRequest(string uri, HttpMethodType method, object query) { this.Request.Uri = this.uriComposer.Compose(this.baseUri, uri, query, this.Request.ParametersAsSegments); this.Request.Data = null; this.Request.PutFilename = string.Empty; this.Request.Expect = false; this.Request.KeepAlive = true; this.Request.MultiPartFormData = null; this.Request.MultiPartFileData = null; this.Request.ContentEncoding = null; this.Request.Method = method; }
public abstract string MakeRequest(string uri, ResponseFormatType responseFormat, HttpMethodType httpMethodType, string body);
public abstract string MakeRequest(string uri, ResponseFormatType responseFormat, HttpMethodType httpMethodType, byte[] body, bool rawBody, bool isPhoto);
public HttpRequestItem(HttpMethodType method, string rawUrl, IDictionary<string, string> queryValues) : this(method, rawUrl) { _rawData.Append(queryValues.ToQueryString()); }
/// <summary> /// OAuthを使ったTwitterAPIへのリクエストを作成します。 /// RequestStreamへの書き込みも行うので非同期推奨。 /// </summary> /// <param name="uri">http(s)://から始まるURI</param> /// <param name="methodType">プロコトルメソッド</param> /// <param name="token">OAuthトークン</param> /// <param name="proxy">プロキシ設定。nullは勘弁。</param> /// <param name="timeout">タイムアウト</param> /// <param name="userAgent">ユーザーエージェント</param> /// <param name="contentType">メディアタイプ。POST・PUTのときのみ指定してください。</param> /// <param name="parameters">パラメータ</param> /// <param name="verifier">OAuth Verifier</param> /// <param name="callback">コールバック。基本oobでOK</param> /// <returns>リクエスト</returns> public static HttpWebRequest GenerateTwitterApiRequest(string uri, HttpMethodType methodType, Token token, IWebProxy proxy, int timeout, string userAgent, string contentType, IEnumerable<FormData> parameters, string verifier, string callback) { parameters = parameters != null ? parameters.ToArray() : new FormData[] { };//遅延実行防止 var ub = new UriBuilder(uri); if ((methodType == HttpMethodType.GET || methodType == HttpMethodType.DELETE)) { if (!string.IsNullOrEmpty(contentType)) throw new ArgumentException("GETまたはDELETEでcontentTypeを指定することはできません。"); if (parameters.Any(param => param.IsFile)) throw new ArgumentException("GETまたはDELETEでファイルを送ることはできません。"); ub.Query = string.Join("&", ub.Query.TrimStart('?').Split('&').Concat( parameters.Select(param => string.Format("{0}={1}", Uri.EscapeDataString(param.Name), Uri.EscapeDataString(param.Content))) )); } var req = (HttpWebRequest)WebRequest.Create(ub.Uri); req.Method = methodType.ToString(); req.Proxy = proxy; req.Timeout = timeout; req.UserAgent = userAgent; req.Headers.Add( HttpRequestHeader.Authorization, OAuthTwitter.CreateAuthorizationHeader( ub.Uri, null, contentType == HttpContentType.MultipartFormData ? null : parameters.Select(_ => new KeyValuePair<string, string>(_.Name, _.Content)), token, verifier, callback, methodType)); if ((methodType == HttpMethodType.POST || methodType == HttpMethodType.PUT) && parameters.Any()) { switch (contentType) { case HttpContentType.ApplicationXWwwFormUrlencoded: if (parameters.Any(param => param.IsFile)) throw new ArgumentException("application/x-www-form-urlencodedでファイルを送ることはできません。"); req.ContentType = "application/x-www-form-urlencoded"; using (var sw = new StreamWriter(req.GetRequestStream())) sw.Write(string.Join("&", parameters.Select(data => Uri.EscapeDataString(data.Name) + "=" + Uri.EscapeDataString(data.Content)))); break; case HttpContentType.MultipartFormData: var boundary = Guid.NewGuid().ToString(); req.ContentType = "multipart/form-data; boundary=" + boundary; using (var stream = req.GetRequestStream()) { foreach (var param in parameters) { stream.WriteText("--" + boundary + "\r\n"); var contentDisposition = new List<string>(); contentDisposition.Add("form-data"); contentDisposition.Add(string.Format(@"name=""{0}""", param.Name)); if (param.IsFile) contentDisposition.Add(string.Format(@"filename=""{0}""", Path.GetFileName(param.Content))); stream.WriteText("Content-Disposition: " + string.Join("; ", contentDisposition)); if (!string.IsNullOrEmpty(param.ContentType)) stream.WriteText("Content-Type: " + param.ContentType); stream.WriteText("\r\n\r\n"); if (!param.IsFile) { stream.WriteText(param.Content); } else { stream.WriteAll(File.ReadAllBytes(param.Content)); } stream.WriteText("\r\n"); } stream.WriteText("--" + boundary + "--"); } break; default: throw new ArgumentException("指定されたcontentTypeには対応していません。"); } } return req; }
public override string MakeRequest(string uri, ResponseFormatType responseFormat, HttpMethodType httpMethodType, byte[] body, bool rawBody, bool isPhoto) { var rawResponse = string.Empty; if (this.AccessToken == null && string.IsNullOrEmpty(this.OAuthTokenKey) && string.IsNullOrEmpty(this.OAuthTokenSecret)) throw new QzoneException("Can not make a request to a Protected Resource without a valid OAuth Access Token Key and Secret", QzoneExceptionType.TOKEN_REQUIRED); if (this.AccessToken == null) this.AccessToken = new AccessToken(this.OAuthConsumer, this.OAuthTokenKey, this.OAuthTokenSecret,this.OpenId); this.OAuthConsumer.ResponseType = responseFormat; this.OAuthConsumer.Scheme = AuthorizationSchemeType.QueryString; switch (httpMethodType) { case HttpMethodType.POST: if (rawBody) this.OAuthConsumer.ResponsePost(uri, body, rawBody, this.AccessToken.TokenKey, this.AccessToken.TokenSecret,this.AccessToken.Openid, isPhoto); else this.OAuthConsumer.ResponsePost(uri, body, this.AccessToken.TokenKey, this.AccessToken.TokenSecret,this.AccessToken.Openid); break; case HttpMethodType.GET: this.OAuthConsumer.ResponseGet(uri, this.AccessToken.TokenKey, this.AccessToken.TokenSecret,this.AccessToken.Openid); break; default: break; } var httpResponse = this.OAuthConsumer.GetResponse() as HttpWebResponse; if (httpResponse != null) { var statusCode = (int)httpResponse.StatusCode; var streamReader = new StreamReader(httpResponse.GetResponseStream()); var responseBody = streamReader.ReadToEnd(); if (statusCode != 200 && statusCode != 201) throw new QzoneException(string.Format("Your request received a response with status code {0}. {1}", statusCode, responseBody), QzoneExceptionType.REQUEST_FAILED, responseBody); return responseBody; } else { throw new QzoneException("Error making request.", QzoneExceptionType.REMOTE_ERROR); } }
public WebResponse RawRequest(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders) { return this.RawRequest(httpMethod, resourcePath, consumerToken, requestHeaders, null); }
public override string MakeRequest(string uri, ResponseFormatType responseFormat, HttpMethodType httpMethodType, string body) { byte[] bodyBytes; if (string.IsNullOrEmpty(body)) { body = string.Empty; } bodyBytes = !string.IsNullOrEmpty(body) ? Encoding.ASCII.GetBytes(body) : null; return this.MakeRequest(uri, responseFormat, httpMethodType, bodyBytes, false); }
public OAuthToken TokenRequest(HttpMethodType httpMethod, string resourcePath, ConsumerToken consumerToken, WebHeaderCollection requestHeaders) { var response = (HttpWebResponse)this.Request(httpMethod, resourcePath, consumerToken, requestHeaders, null, null); var streamReader = new StreamReader(response.GetResponseStream()); var responseBody = streamReader.ReadToEnd(); switch (response.StatusCode) { case HttpStatusCode.OK: return ParseTokenResponse(responseBody); default: throw new Exception(string.Format("{0} - {1}", response.StatusCode, responseBody)); } }