/// <summary>Add a new pet to the store</summary> /// <param name="body">Pet object that needs to be added to the store</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task AddPetAsync(Pet body, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "pet"); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body)); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "405") { throw new SwaggerException("Invalid input", status_, responseData_, null); } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task FromBodyTestAsync(GeoPoint location, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/FromBodyTest"); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(location, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() })); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "204") { return; } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
public void ContentWithPairMatchesBecauseNoParameters() { // Will always match SimulationConditionEvaluator e = new SimulationConditionEvaluator(); SimulationCondition c = new SimulationCondition(); System.Net.Http.HttpContent content = new System.Net.Http.StringContent("a=b", Encoding.UTF8, "application/json"); Assert.IsTrue(e.MatchesBodyParameters(c, content)); }
public void ContentWithOneOfTwoMatchingPairMatches() { // Will always match SimulationConditionEvaluator e = new SimulationConditionEvaluator(); SimulationCondition c = new SimulationCondition(); c.Parameter("c", "d"); c.Parameter("a", "b"); System.Net.Http.HttpContent content = new System.Net.Http.StringContent("a=b", Encoding.UTF8, "application/json"); Assert.IsFalse(e.MatchesBodyParameters(c, content)); }
private HttpContent ContentPart(IJsonHelper helper, string name, object @object, bool persistent) { var json = helper.Serialize(@object); var part = new StringContent(json.ToString(), Encoding.UTF8, "application/json"); part.Headers.ContentType.Parameters.Add( new System.Net.Http.Headers.NameValueHeaderValue("model", name)); if (persistent) { part.Headers.ContentType.Parameters.Add( new System.Net.Http.Headers.NameValueHeaderValue("persistent")); } return part; }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task ApiTasksCompleteByIdPostAsync(int id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (id == null) { throw new System.ArgumentNullException("id"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/api/tasks/complete/{id}"); urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(System.Convert.ToString(id, System.Globalization.CultureInfo.InvariantCulture))); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task RefreshAsync(System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/Refresh"); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "204") { return; } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
/// <summary> /// /// </summary> private void startElasticsearchWatcherClient() { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); var content = new System.Net.Http.StringContent("{\"trigger\":{\"schedule\":{\"interval\":\"10s\"}},\"input\":{\"search\":{\"request\":{\"body\":{\"query\":{\"term\":{\"alarmType\":{\"value\":\"critical\"}}}}}}},\"condition\":{\"always\":{}},\"actions\":{\"webAction\":{\"webhook\":{\"port\":5000,\"host\":\"localhost\",\"path\":\"/api/WatcherEvents/CriticalAlarm\",\"method\":\"post\",\"headers\":{\"Content-Type\":\"application/json;charset=utf-8\"},\"body\":\"{{ctx.payload.hits.total}}\"}}}}"); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var response = httpClient.PutAsync("http://localhost:9200/_watcher/watch/critical-alarm-watch", content).Result; }
public void ContentWithTwoOfThreeMatchingPairMatches() { SimulationConditionEvaluator e = new SimulationConditionEvaluator(); SimulationCondition c = new SimulationCondition(); c.Parameter("c", "d"); c.Parameter("a", "b"); System.Net.Http.HttpContent content = new System.Net.Http.StringContent("a=b&c=d&e=f", Encoding.UTF8, "application/json"); Assert.IsTrue(e.MatchesBodyParameters(c, content)); }
/// <summary>Place an order for a pet</summary> /// <param name="body">order placed for purchasing the pet</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>successful operation</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<Order> PlaceOrderAsync(Order body, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "store/order"); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body)); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(Order); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length)); return result_; } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ == "400") { throw new SwaggerException("Invalid Order", status_, responseData_, null); } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(Order); } }
/// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task PutAsync(string id, Movie movie, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/v1/Movie/{id}"); urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(movie, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "400") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ProblemDetails); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <ProblemDetails>(responseData_, _settings.Value); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new SwaggerException <ProblemDetails>("A server side error occurred.", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ == "404") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ProblemDetails); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <ProblemDetails>(responseData_, _settings.Value); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new SwaggerException <ProblemDetails>("A server side error occurred.", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ == "204") { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ProblemDetails); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <ProblemDetails>(responseData_, _settings.Value); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new SwaggerException <ProblemDetails>("A server side error occurred.", (int)response_.StatusCode, responseData_, headers_, result_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task PostAsync(CreateCompanyCommand query, System.Threading.CancellationToken cancellationToken) { if (query == null) { throw new System.ArgumentNullException("query"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Company"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(query, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 201) { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
public Schema Solve(Schema inputSchema, bool useMemoryCache) { string solveUrl; var pathType = GetPathType(); if (pathType == PathType.NonresponsiveUrl) { return(null); } if (pathType == PathType.GrasshopperDefinition || pathType == PathType.ComponentGuid) { solveUrl = Servers.GetSolveUrl(); if (!string.IsNullOrEmpty(_cacheKey)) { inputSchema.Pointer = _cacheKey; } } else { int index = Path.LastIndexOf('/'); solveUrl = Path.Substring(0, index + 1) + "solve"; } string inputJson = JsonConvert.SerializeObject(inputSchema); if (useMemoryCache && inputSchema.Algo == null) { var cachedResults = Hops.MemoryCache.Get(inputJson); if (cachedResults != null) { return(cachedResults); } } using (var content = new System.Net.Http.StringContent(inputJson, Encoding.UTF8, "application/json")) { var postTask = HttpClient.PostAsync(solveUrl, content); var responseMessage = postTask.Result; if (responseMessage.StatusCode == System.Net.HttpStatusCode.InternalServerError) { bool fileExists = File.Exists(Path); if (fileExists && string.IsNullOrEmpty(inputSchema.Algo)) { var bytes = System.IO.File.ReadAllBytes(Path); string base64 = Convert.ToBase64String(bytes); inputSchema.Algo = base64; inputJson = JsonConvert.SerializeObject(inputSchema); var content2 = new System.Net.Http.StringContent(inputJson, Encoding.UTF8, "application/json"); postTask = HttpClient.PostAsync(solveUrl, content2); responseMessage = postTask.Result; if (responseMessage.StatusCode == System.Net.HttpStatusCode.InternalServerError) { var badSchema = new Schema(); badSchema.Errors.Add("Unable to solve on compute"); return(badSchema); } } else { if (!fileExists && string.IsNullOrEmpty(inputSchema.Algo) && GetPathType() == PathType.GrasshopperDefinition) { var badSchema = new Schema(); badSchema.Errors.Add($"Unable to find file: {Path}"); return(badSchema); } } } var remoteSolvedData = responseMessage.Content; var stringResult = remoteSolvedData.ReadAsStringAsync().Result; var schema = JsonConvert.DeserializeObject <Resthopper.IO.Schema>(stringResult); if (useMemoryCache && inputSchema.Algo == null) { Hops.MemoryCache.Set(inputJson, schema); } _cacheKey = schema.Pointer; return(schema); } }
public async Task <RequestResult <AuthenticateResultModel> > AuthenticateAsync(AuthenticateModel model, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/TokenAuth/Authenticate"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, CancellationToken.None).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); // if (status_ == "200") //{ var objectResponse_ = await ReadObjectResponseAsync <RequestResult <AuthenticateResultModel> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); //} //else //if (status_ != "200" && status_ != "204") //{ // var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); // throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); //} //return default(RequestResult<AuthenticateResultModel>); } catch (Exception ex) { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, null, ex); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
public void CompressedContent_Constructor_ConstructsOkWithContentAndDeflateEncoding() { var innerContent = new System.Net.Http.StringContent("Test"); var compressedContent = new CompressedContent(innerContent, "deflate"); }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task SaveAdsAsync(System.Collections.Generic.IEnumerable <TableUser> data, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/SaveAds"); var client_ = _httpClient; client_.Timeout = TimeSpan.FromMinutes(30); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent( Newtonsoft.Json.JsonConvert.SerializeObject(data, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(true); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException( "The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } catch (Exception e) { e.ToString(); } finally { } }
public void CompressedContent_Constructor_ThrowsOnUnsupportedContentType() { var innerContent = new System.Net.Http.StringContent("Test"); var compressedContent = new CompressedContent(innerContent, "123"); }
public void CompressedContent_Constructor_ThrowsOnNullEncoding() { var innerContent = new System.Net.Http.StringContent("Test"); var compressedContent = new CompressedContent(innerContent, null); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Create a user</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <User> CreateAsync(User body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/users"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "201") { var objectResponse_ = await ReadObjectResponseAsync <User>(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else if (status_ == "400") { var objectResponse_ = await ReadObjectResponseAsync <ProblemDetails>(response_, headers_).ConfigureAwait(false); throw new ApiException <ProblemDetails>("Bad Request", (int)response_.StatusCode, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(User)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="PersonsClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<Person> ThrowAsync(System.Guid id, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Persons/Throw"); if (id == null) throw new System.ArgumentNullException("id"); else url_ += string.Format("id={0}&", System.Uri.EscapeDataString(id.ToString())); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(Person); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); return result_; } catch (System.Exception exception) { throw new PersonsClientException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ == "500") { var result_ = default(PersonNotFoundException); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<PersonNotFoundException>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); } catch (System.Exception exception) { throw new PersonsClientException("Could not deserialize the response body.", status_, responseData_, exception); } if (result_ == null) result_ = new PersonNotFoundException(); result_.Data.Add("HttpStatus", status_); result_.Data.Add("ResponseData", System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length)); throw new PersonsClientException<PersonNotFoundException>("A server side error occurred.", status_, responseData_, result_, result_); } else if (status_ != "200" && status_ != "204") throw new PersonsClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(Person); } }
/// <summary>Get List by character</summary> /// <exception cref="GlossaryClientException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <ResponseModelOfGlossaryModel> Glossary_GetByCharacterAsync(RequestModelOfChar request, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/GetByCharacter"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(request, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ResponseModelOfGlossaryModel); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseModelOfGlossaryModel>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new GlossaryClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new GlossaryClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(ResponseModelOfGlossaryModel)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task ApiTasksPostAsync(ScheduledTaskDTO task = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/api/tasks"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(task, _settings.Value)); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <FileResponse> CreateLabelAsync(LabelDTO label, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/Label/label"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(label, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(fileResponse_); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(FileResponse)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
void GetRemoteDescription() { bool performPost = false; string address = null; var pathType = GetPathType(); switch (pathType) { case PathType.GrasshopperDefinition: { if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) || File.Exists(Path)) { address = Path; performPost = true; } } break; case PathType.ComponentGuid: address = Servers.GetDescriptionUrl(Guid.Parse(Path)); break; case PathType.Server: address = Path; break; case PathType.NonresponsiveUrl: break; } if (address == null) { return; } IoResponseSchema responseSchema = null; System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> responseTask = null; IDisposable contentToDispose = null; if (performPost) { string postUrl = Servers.GetDescriptionPostUrl(); var schema = new Schema(); if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { schema.Pointer = address; } else { var bytes = System.IO.File.ReadAllBytes(address); schema.Algo = Convert.ToBase64String(bytes); } string inputJson = JsonConvert.SerializeObject(schema); var content = new System.Net.Http.StringContent(inputJson, Encoding.UTF8, "application/json"); responseTask = HttpClient.PostAsync(postUrl, content); contentToDispose = content; } else { responseTask = HttpClient.GetAsync(address); } if (responseTask != null) { var responseMessage = responseTask.Result; var remoteSolvedData = responseMessage.Content; var stringResult = remoteSolvedData.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(stringResult)) { responseSchema = JsonConvert.DeserializeObject <Resthopper.IO.IoResponseSchema>(stringResult); _cacheKey = responseSchema.CacheKey; } } if (contentToDispose != null) { contentToDispose.Dispose(); } if (responseSchema != null) { _description = responseSchema.Description; _customIcon = null; if (!string.IsNullOrWhiteSpace(responseSchema.Icon)) { try { byte[] bytes = Convert.FromBase64String(responseSchema.Icon); using (var ms = new MemoryStream(bytes)) { _customIcon = new System.Drawing.Bitmap(ms); } } catch (Exception) { } } _inputParams = new Dictionary <string, Tuple <InputParamSchema, IGH_Param> >(); _outputParams = new Dictionary <string, IGH_Param>(); foreach (var input in responseSchema.Inputs) { string inputParamName = input.Name; if (inputParamName.StartsWith("RH_IN:")) { var chunks = inputParamName.Split(new char[] { ':' }); inputParamName = chunks[chunks.Length - 1]; } _inputParams[inputParamName] = Tuple.Create(input, ParamFromIoResponseSchema(input)); } foreach (var output in responseSchema.Outputs) { string outputParamName = output.Name; if (outputParamName.StartsWith("RH_OUT:")) { var chunks = outputParamName.Split(new char[] { ':' }); outputParamName = chunks[chunks.Length - 1]; } _outputParams[outputParamName] = ParamFromIoResponseSchema(output); } } }
/// <summary>Creates list of users with given input array</summary> /// <param name="body">List of user object</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>successful operation</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task CreateUsersWithListInputAsync(System.Collections.Generic.IEnumerable<User> body, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "user/createWithList"); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body)); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); } }
/// <summary> /// /// </summary> /// <returns></returns> public Task <string> Handle() { var rlt = Task.Run <string>(() => { return(""); }); Result = new ApiResult <IResponse> { node = XCore.WebNode, code = "-1", success = false, message = "unkown error" }; if (string.IsNullOrEmpty(ApiHost)) { Result.code = "400"; Result.message = "request host not set"; } else if (string.IsNullOrEmpty(ApiPath)) { Result.code = "400"; Result.message = "request path not set"; } else { System.Net.Http.HttpClient http = null; Task <System.Net.Http.HttpResponseMessage> task = null; if (Certificate == null) { http = new System.Net.Http.HttpClient(); } else { var handler = new System.Net.Http.HttpClientHandler(); handler.ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual; handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; handler.ClientCertificates.Add(Certificate); http = new System.Net.Http.HttpClient(handler); } http.BaseAddress = new System.Uri(ApiHost); if (Method == "GET") { var query = RequestBody as string; if (!string.IsNullOrEmpty(query)) { var link = ApiPath.IndexOf('?') < 0 ? '?' : '&'; ApiPath += query[0] == '?' || query[0] == '&' ? query : link + query; } if (HttpRequestHeaders != null) { foreach (var kv in HttpRequestHeaders) { http.DefaultRequestHeaders.Add(kv.Key, kv.Value); } } task = http.GetAsync(ApiPath); } else { System.Net.Http.HttpContent content = null; var text = RequestBody as string; var bytes = RequestBody as byte[]; if (bytes != null) { content = new System.Net.Http.ByteArrayContent(bytes); } else if (!string.IsNullOrEmpty(text)) { content = new System.Net.Http.StringContent(text, Encoding, ContentType); } else if (RequestBody != null) { content = new System.Net.Http.StringContent(Json.ToString(RequestBody), Encoding, ContentType); } else { content = new System.Net.Http.ByteArrayContent(new byte[0]); } if (HttpRequestHeaders != null) { foreach (var kv in HttpRequestHeaders) { content.Headers.Add(kv.Key, kv.Value); } } task = http.PostAsync(ApiPath, content); } task.Result.Content.ReadAsStringAsync().ContinueWith((res) => { ResponseBody = res.Result; HttpResponseHeaders = new Dictionary <string, string>(); foreach (var item in task.Result.Headers) { var em = item.Value.GetEnumerator(); if (em.MoveNext()) { HttpResponseHeaders.Add(item.Key.ToLower(), em.Current); } } rlt = Task.Run <string>(() => { return(res.Result); }); }).Wait(); } return(rlt); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>首页接口</summary> /// <param name="model">模型</param> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <Tourism.STD.Models.SmallApp.Index.IndexForOutput> > IndexPageAsync(Tourism.STD.Models.SmallApp.Index.IndexForInput model, System.Threading.CancellationToken cancellationToken) { if (model == null) { throw new System.ArgumentNullException("model"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("SmallAppApi/Index/IndexPage"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <Tourism.STD.Models.SmallApp.Index.IndexForOutput> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <CartItems> AddAsync(long id, CartItems items, System.Threading.CancellationToken cancellationToken) { if (id == null) { throw new System.ArgumentNullException("id"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Cart/Add/{id}"); urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(items, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(CartItems); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <CartItems>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ == "400") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(CartError); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <CartError>(responseData_, _settings.Value); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new SwaggerException <CartError>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(CartItems)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <summary> /// 调用第三方PhantomJs /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { using (var client = new System.Net.Http.HttpClient()) { client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json")); var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result; var responseStream = response.Content.ReadAsStreamAsync().Result; using (var fileStream = new System.IO.FileStream("content.jpg", System.IO.FileMode.Create)) { responseStream.CopyTo(fileStream); } Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***"); Console.WriteLine(response.Headers); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <System.DateTime> AddDaysAsync(System.DateTime date, int days, System.Threading.CancellationToken cancellationToken) { if (date == null) { throw new System.ArgumentNullException("date"); } if (days == null) { throw new System.ArgumentNullException("days"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/api/Date/AddDays?"); urlBuilder_.Append("date=").Append(System.Uri.EscapeDataString(date.ToString("s", System.Globalization.CultureInfo.InvariantCulture))).Append("&"); urlBuilder_.Append("days=").Append(System.Uri.EscapeDataString(System.Convert.ToString(days, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); urlBuilder_.Length--; var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(System.DateTime); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.DateTime>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception); } } else if (status_ != "200" && status_ != "204") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null); } return(default(System.DateTime)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
/// <exception cref="AnnouncementException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <FileResponse> PutAnnouncementAsync(System.Guid id, AnnouncementForUpdate announcement, System.Threading.CancellationToken cancellationToken) { if (id == null) { throw new System.ArgumentNullException("id"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/announcements/{id}"); urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(announcement, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206" || status_ == "201") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, client_, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(fileResponse_); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new AnnouncementException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(FileResponse)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
private async void logins_Click(object sender, RoutedEventArgs e) { //try //{ // StorageFolder folder = ApplicationData.Current.LocalCacheFolder; // var imgfile = await folder.GetFileAsync("ValidateCode.jpg"); // await imgfile.DeleteAsync(); //} //catch (Exception ex) //{ // ; //} Uri login = new Uri("http://222.30.32.10/stdloginAction.do"); string parma = "operation=&usercode_text="+user.Text+"&userpwd_text="+pwd.Password+"&checkcode_text=" + vldcode.Text + "&submittype=%C8%B7+%C8%CF"; System.Net.Http.HttpContent hc = new System.Net.Http.StringContent(parma, System.Text.UnicodeEncoding.UTF8, "application/x-www-form-urlencoded"); System.Net.Http.HttpClient connlogin = new System.Net.Http.HttpClient(); connlogin.DefaultRequestHeaders.Add("cookie", this.cookie); System.Net.Http.HttpResponseMessage res = await connlogin.PostAsync(login, hc); byte[] resbyte = res.Content.ReadAsByteArrayAsync().Result; string posts = TextReader.GBK.gbk2utf16(resbyte); if (posts.IndexOf("请输入正确的验证码!") != -1) { await new MessageDialog("请输入正确的验证码!").ShowAsync(); vldcode.Text = ""; } else if (posts.IndexOf("用户不存在或密码错误!") != -1) { await new MessageDialog("用户名不存在或密码错误").ShowAsync(); user.Text = ""; pwd.Password = ""; vldcode.Text = ""; } else { await new MessageDialog("登录成功").ShowAsync(); ApplicationData.Current.LocalSettings.Values["login"] = true; ApplicationData.Current.LocalSettings.Values["cookie"] = this.cookie; this.Frame.Navigate(typeof(MainPage)); } }
/// <summary>Runtime makes this request in order to submit an error response. It can be either a function error, or a runtime error. Error will be served in response to the invoke.</summary> /// <returns>Accepted</returns> /// <exception cref="RuntimeApiClientException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <SwaggerResponse <StatusResponse> > Error2Async(string awsRequestId, string lambda_Runtime_Function_Error_Type, string errorJson, System.Threading.CancellationToken cancellationToken) { if (awsRequestId == null) { throw new System.ArgumentNullException("awsRequestId"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/runtime/invocation/{AwsRequestId}/error"); urlBuilder_.Replace("{AwsRequestId}", System.Uri.EscapeDataString(ConvertToString(awsRequestId, System.Globalization.CultureInfo.InvariantCulture))); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { if (lambda_Runtime_Function_Error_Type != null) { request_.Headers.TryAddWithoutValidation("Lambda-Runtime-Function-Error-Type", ConvertToString(lambda_Runtime_Function_Error_Type, System.Globalization.CultureInfo.InvariantCulture)); } using (var content_ = new System.Net.Http.StringContent(errorJson)) { content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(ErrorContentType); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "202") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(StatusResponse); try { result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <StatusResponse>(responseData_); return(new SwaggerResponse <StatusResponse>((int)response_.StatusCode, headers_, result_)); } catch (System.Exception exception_) { throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ == "400") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ErrorResponse); try { result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <ErrorResponse>(responseData_); } catch (System.Exception exception_) { throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new RuntimeApiClientException <ErrorResponse>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ == "403") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(ErrorResponse); try { result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <ErrorResponse>(responseData_); } catch (System.Exception exception_) { throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new RuntimeApiClientException <ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ == "500") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new RuntimeApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(new SwaggerResponse <StatusResponse>((int)response_.StatusCode, headers_, default(StatusResponse))); } finally { if (response_ != null) { response_.Dispose(); } } } } } finally { } }
public void TwoConditionsSecondOneMatches() { SimulationConditionEvaluator e = new SimulationConditionEvaluator(); SimulationCondition c1 = new SimulationCondition(); c1.Parameter("c", "d"); c1.Parameter("g", "h"); SimulationCondition c2 = new SimulationCondition(); c2.Parameter("c", "d"); c2.Parameter("e", "f"); System.Net.Http.HttpContent content = new System.Net.Http.StringContent("a=b&c=d&e=f", Encoding.UTF8, "application/json"); Assert.IsFalse(e.MatchesBodyParameters(c1, content)); Assert.IsTrue(e.MatchesBodyParameters(c2, content)); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>CancelInvoice cancels a currently open invoice. If the invoice is already /// <br/>canceled, this call will succeed. If the invoice is already settled, it will /// <br/>fail.</summary> /// <returns>A successful response.</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async Task <InvoicesrpcCancelInvoiceResp> CancelInvoiceAsync(InvoicesrpcCancelInvoiceMsg body, CancellationToken cancellationToken) { if (body == null) { throw new System.ArgumentNullException("body"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/v2/invoices/cancel"); var client_ = _httpClient; var disposeClient_ = false; try { using var request_ = new System.Net.Http.HttpRequestMessage(); var content_ = new System.Net.Http.StringContent( Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add( System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(InvoicesrpcCancelInvoiceResp); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <InvoicesrpcCancelInvoiceResp>( responseData_, _settings.Value); return(result_); } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_.ToString(), responseData_, headers_, exception); } } else { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException( "The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_.ToString(), responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } finally { if (disposeClient_) { client_.Dispose(); } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <string> UploadAsync(AccountDump accountDump, System.Threading.CancellationToken cancellationToken) { if (accountDump == null) { throw new System.ArgumentNullException("accountDump"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Account"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(accountDump, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <string>(response_, headers_).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
public SolrWebResponse Execute(SolrWebRequest request) { var paramStr = string.Join("&", request.Parameters.Select(x => string.Format("{0}={1}", x.Name, x.Value)).ToArray()); _endpoint = _endpoint.EndsWith("/") ? _endpoint.TrimEnd('/') : _endpoint; request.ActionUrl = request.ActionUrl.StartsWith("/") ? request.ActionUrl.TrimStart('/') : request.ActionUrl; paramStr = string.Format("{0}/{1}?{2}", _endpoint, request.ActionUrl, paramStr.Substring(0, paramStr.Length)); var response = new SolrWebResponse(); response.ResponseUri = new Uri(paramStr); #if NET40 || PORTABLE40 || PORTABLE HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(paramStr); if (request.Method == SolrWebMethod.GET) { using (var webResponse = (HttpWebResponse)(System.Threading.Tasks.Task <WebResponse> .Factory.FromAsync( webRequest.BeginGetResponse, webRequest.EndGetResponse, null)).Result) { using (System.IO.Stream stream = webResponse.GetResponseStream()) { var reader = new System.IO.StreamReader(stream, Encoding.UTF8); response.Content = reader.ReadToEnd(); response.StatusCode = webResponse.StatusCode; } } } else { webRequest.Method = "POST"; webRequest.ContentType = "application/json"; CurrentRequest = request; var result = (HttpWebRequest)webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest).AsyncState; return(response); } #elif NET35 var webRequest = (HttpWebRequest)WebRequest.Create(paramStr); if (request.Method == SolrWebMethod.GET) { using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { var encoding = Encoding.GetEncoding(webResponse.CharacterSet); using (var responseStream = webResponse.GetResponseStream()) { using (var reader = new System.IO.StreamReader(responseStream, encoding)) { response.Content = reader.ReadToEnd(); response.StatusCode = webResponse.StatusCode; } } } } else { webRequest.Method = "POST"; webRequest.ContentType = "application/json"; webRequest.ContentLength = request.Body.Length; var data = Encoding.UTF8.GetBytes(request.Body); using (var stream = webRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); } var webResponse = (HttpWebResponse)webRequest.GetResponse(); response.Content = new System.IO.StreamReader(webResponse.GetResponseStream()).ReadToEnd(); response.StatusCode = webResponse.StatusCode; } #else var client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); if (request.Method == SolrWebMethod.GET) { var webResponse = client.GetAsync(paramStr).Result; response.Content = webResponse.Content.ReadAsStringAsync().Result; response.StatusCode = webResponse.StatusCode; } else { var content = new System.Net.Http.StringContent(request.Body, Encoding.UTF8, "application/json"); var webResponse = client.PostAsync(paramStr, content).Result; //var webResponse = client.GetAsync(paramStr).Result; response.Content = webResponse.Content.ReadAsStringAsync().Result; response.StatusCode = webResponse.StatusCode; } #endif return(response); }
public static void CaptureAsJPEG() { using (var client = new System.Net.Http.HttpClient()) { client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors var pageRequestJson = new System.Net.Http.StringContent(File.ReadAllText("request.json")); var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result; var responseStream = response.Content.ReadAsStreamAsync().Result; //using (var fileStream = new FileStream("content123455.jpg", FileMode.Create)) //{ // responseStream.CopyTo(fileStream); //} using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"))) { string retString = myStreamReader.ReadToEnd(); } var ms = new MemoryStream(); responseStream.CopyTo(ms); //responseStream.Position = 0; //byte[] buffer = new byte[2048]; //int bytesRead = 0; //while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0) //{ // ms.Write(buffer, 0, bytesRead); //} ms.Position = 0; Bitmap destBmp = new Bitmap(ms);//create bmp instance from stream above destBmp.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");//save bmp to the path you want //var image = System.Drawing.Image.FromStream(ms); //image.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"); //ms.Close(); Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***"); Console.WriteLine(response.Headers); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task PutAsync(int id, string value, System.Threading.CancellationToken cancellationToken) { if (id == null) { throw new System.ArgumentNullException("id"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("api/Books/{id}"); urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(value, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task SaveItemsAsync(GenericRequestOfAddressAndPerson request, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/SaveItems"); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(request, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() })); content_.Headers.ContentType.MediaType = "application/json"; request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "204") { return; } else if (status_ == "450") { var result_ = default(System.Exception); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Exception>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); } catch (System.Exception exception) { throw new GeoClientException("Could not deserialize the response body.", status_, responseData_, exception); } if (result_ == null) result_ = new System.Exception(); result_.Data.Add("HttpStatus", status_); result_.Data.Add("ResponseData", System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length)); throw new GeoClientException<System.Exception>("A custom error occured.", status_, responseData_, result_, result_); } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
void GetRemoteDescription() { bool performPost = false; string address = null; var pathType = GetPathType(); switch (pathType) { case PathType.GrasshopperDefinition: { if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) || File.Exists(Path)) { address = Path; performPost = true; } } break; case PathType.ComponentGuid: address = Servers.GetDescriptionUrl(Guid.Parse(Path)); break; case PathType.Server: address = Path; break; case PathType.NonresponsiveUrl: break; } if (address == null) { return; } IoResponseSchema responseSchema = null; System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> responseTask; IDisposable contentToDispose = null; if (performPost) { string postUrl = Servers.GetDescriptionPostUrl(); var schema = new Schema(); if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { schema.Pointer = address; } else { var bytes = System.IO.File.ReadAllBytes(address); schema.Algo = Convert.ToBase64String(bytes); } string inputJson = JsonConvert.SerializeObject(schema); var content = new System.Net.Http.StringContent(inputJson, Encoding.UTF8, "application/json"); responseTask = HttpClient.PostAsync(postUrl, content); contentToDispose = content; } else { responseTask = HttpClient.GetAsync(address); } if (responseTask != null) { var responseMessage = responseTask.Result; var remoteSolvedData = responseMessage.Content; var stringResult = remoteSolvedData.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(stringResult)) { responseSchema = JsonConvert.DeserializeObject <Resthopper.IO.IoResponseSchema>(stringResult); _cacheKey = responseSchema.CacheKey; } } if (contentToDispose != null) { contentToDispose.Dispose(); } if (responseSchema != null) { _description = responseSchema.Description; _customIcon = null; if (!string.IsNullOrWhiteSpace(responseSchema.Icon)) { try { // Use reflection until we update requirements for Hops to run on a newer service release of Rhino string svg = responseSchema.Icon; // Check for some hope that the string is svg. Pre-7.7 has a bug where it could crash // Rhino with invalid svg if (svg.IndexOf("svg", StringComparison.InvariantCultureIgnoreCase) < 0 || svg.IndexOf("xmlns", StringComparison.InvariantCultureIgnoreCase) < 0) { svg = null; } if (svg != null) { var method = typeof(Rhino.UI.DrawingUtilities).GetMethod("BitmapFromSvg"); if (method != null) { _customIcon = method.Invoke(null, new object[] { svg, 24, 24 }) as System.Drawing.Bitmap; } //_customIcon = Rhino.UI.DrawingUtilities.BitmapFromSvg(responseSchema.Icon, 24, 24); } if (_customIcon == null) { byte[] bytes = Convert.FromBase64String(responseSchema.Icon); using (var ms = new MemoryStream(bytes)) { _customIcon = new System.Drawing.Bitmap(ms); } } } catch (Exception) { } } _inputParams = new Dictionary <string, Tuple <InputParamSchema, IGH_Param> >(); _outputParams = new Dictionary <string, IGH_Param>(); foreach (var input in responseSchema.Inputs) { string inputParamName = input.Name; if (inputParamName.StartsWith("RH_IN:")) { var chunks = inputParamName.Split(new char[] { ':' }); inputParamName = chunks[chunks.Length - 1]; } _inputParams[inputParamName] = Tuple.Create(input, ParamFromIoResponseSchema(input)); } foreach (var output in responseSchema.Outputs) { string outputParamName = output.Name; if (outputParamName.StartsWith("RH_OUT:")) { var chunks = outputParamName.Split(new char[] { ':' }); outputParamName = chunks[chunks.Length - 1]; } _outputParams[outputParamName] = ParamFromIoResponseSchema(output); } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="PersonsClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<Person>> Find2Async(Gender? gender, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Persons/find2"); if (gender != null) url_ += string.Format("gender={0}&", System.Uri.EscapeDataString(gender.Value.ToString())); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(System.Collections.ObjectModel.ObservableCollection<Person>); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<Person>>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); return result_; } catch (System.Exception exception) { throw new PersonsClientException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ != "200" && status_ != "204") throw new PersonsClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(System.Collections.ObjectModel.ObservableCollection<Person>); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Update patient</summary> /// <param name="authorisation">Authorisation</param> /// <param name="body">Patient to be updated</param> /// <param name="patientId">Patient ID</param> /// <returns>successful operation</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <Patient> PutPatientAsync(string authorisation, Patient body, int patientId, System.Threading.CancellationToken cancellationToken) { if (patientId == null) { throw new System.ArgumentNullException("patientId"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/patients/{patientId}"); urlBuilder_.Replace("{patientId}", System.Uri.EscapeDataString(ConvertToString(patientId, System.Globalization.CultureInfo.InvariantCulture))); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { if (authorisation == null) { throw new System.ArgumentNullException("authorisation"); } request_.Headers.TryAddWithoutValidation("Authorisation", ConvertToString(authorisation, System.Globalization.CultureInfo.InvariantCulture)); var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("*/*")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var objectResponse_ = await ReadJsonObjectResponseAsync <Patient>(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else if (status_ == "201") { string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("Created", (int)response_.StatusCode, responseText_, headers_, null); } else if (status_ == "401") { string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("Unauthorized", (int)response_.StatusCode, responseText_, headers_, null); } else if (status_ == "403") { string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("Forbidden", (int)response_.StatusCode, responseText_, headers_, null); } else if (status_ == "404") { string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("Not Found", (int)response_.StatusCode, responseText_, headers_, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(Patient)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task FromUriTestAsync(double? latitude, double? longitude, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Geo/FromUriTest"); if (latitude == null) throw new System.ArgumentNullException("latitude"); else url_ += string.Format("Latitude={0}&", System.Uri.EscapeDataString(latitude.Value.ToString())); if (longitude == null) throw new System.ArgumentNullException("longitude"); else url_ += string.Format("Longitude={0}&", System.Uri.EscapeDataString(longitude.Value.ToString())); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.StringContent(string.Empty); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "204") { return; } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
public async Task Invoke(HttpContext context) { //var apiRoute = context.Request.Path.Value; //Enum.TryParse(context.Request.Method, out HttpMethod httpMethod); //Read the Header var request = context.Request; string authHeader = context.Request.Headers["Authorization"]; string pandaHeader = context.Request.Headers["Panda"]; if (string.IsNullOrEmpty(pandaHeader)) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Secure Key Not found'] }"); return; } var SecureKey = _configuration["SecureKey:Self"]; if (SecureKey != pandaHeader) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Secure Key Invalid'] }"); return; } ClaimsPrincipal pcp = null; if (!string.IsNullOrEmpty(authHeader)) { authHeader = authHeader.Replace("Bearer ", ""); pcp = _jwtTokenService.GetPrincipalFromExpiredToken(authHeader); if (pcp == null) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Token Invalid'] }"); return; } } #region BodyModified if (request.Path.Value.Contains("/api") && !request.Path.Value.ToLower().Contains("value")) { var stream = request.Body; var originalContent = new StreamReader(stream).ReadToEnd(); var notModified = true; try { dynamic dataSource = JsonConvert.DeserializeObject(originalContent); if (dataSource != null) { dataSource.Token = authHeader; var json = JsonConvert.SerializeObject(dataSource); var requestContent = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); stream = await requestContent.ReadAsStreamAsync(); notModified = false; } } catch { notModified = true; } if (notModified) { var requestData = Encoding.UTF8.GetBytes(originalContent); stream = new MemoryStream(requestData); } request.Body = stream; } #endregion await _next(context); }