本文整理汇总了C#中System.Net.Http.StringContent类的典型用法代码示例。如果您正苦于以下问题:C# StringContent类的具体用法?C# StringContent怎么用?C# StringContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StringContent类属于System.Net.Http命名空间,在下文中一共展示了StringContent类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: sendPost
public void sendPost()
{
// Définition des variables qui seront envoyés
HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
HttpContent fileStreamContent = new StreamContent(paramFileStream);
//HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
// formData.Add(bytesContent, "file2", "file2");
try
{
var response = client.PostAsync(actionUrl, formData).Result;
MessageBox.Show(response.ToString());
if (!response.IsSuccessStatusCode)
{
MessageBox.Show("Erreur de réponse");
}
}
catch (Exception Error)
{
MessageBox.Show(Error.Message);
}
finally
{
client.CancelPendingRequests();
}
}
}
开发者ID:microint,项目名称:WindowsFormsPostRequest,代码行数:34,代码来源:Form1.cs
示例2: Execute
public async Task<JObject> Execute()
{
if (!NetworkInterface.GetIsNetworkAvailable())
throw new Exception("Network is not available.");
var uri = GetFullUri(_parameters);
var request = WebRequest.CreateHttp(uri);
request.Method = _method;
Debug.WriteLine("Invoking " + uri);
JObject response = null;
var httpClient = new HttpClient();
if (_method == "GET")
{
HttpResponseMessage responseMessage = await httpClient.GetAsync(uri);
string content = await responseMessage.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
response = JObject.Parse(content);
}
else if (_method == "POST")
{
var postContent = new StringContent(_postParameters.ConstructQueryString());
postContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, postContent);
string content = await responseMessage.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
response = JObject.Parse(content);
}
return response;
}
开发者ID:justdude,项目名称:meridian,代码行数:34,代码来源:CoreRequest.cs
示例3: Request
public Task<string> Request(ApiClientRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (string.IsNullOrWhiteSpace(request.Username)) throw new ArgumentException("Username is required", nameof(request));
if (string.IsNullOrWhiteSpace(request.Password)) throw new ArgumentException("Password is required", nameof(request));
if (string.IsNullOrWhiteSpace(request.BaseAddress)) throw new ArgumentException("BaseAddress is required", nameof(request));
if (string.IsNullOrWhiteSpace(request.RequestUri)) throw new ArgumentException("RequestUri is required", nameof(request));
if (string.IsNullOrWhiteSpace(request.Content)) throw new ArgumentException("Content is required", nameof(request));
using (var httpClient = CreateHttpClient(request.Username, request.Password, request.BaseAddress))
using (var content = new StringContent(request.Content, Encoding.UTF8, "application/soap+xml"))
{
var response = httpClient.PostAsync(request.RequestUri, content).Result;
if (!response.IsSuccessStatusCode)
{
var error = response.Content.ReadAsStringAsync().Result;
throw new InvalidOperationException($"{error} ({response.StatusCode} {response.ReasonPhrase})");
}
return response
.Content
.ReadAsStringAsync();
}
}
开发者ID:danpadmore,项目名称:homebased,代码行数:26,代码来源:SoapApiClient.cs
示例4: CreateInvalidGrantTokenResponseMessage
public static HttpResponseMessage CreateInvalidGrantTokenResponseMessage()
{
HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
HttpContent content = new StringContent("{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS70002: Error validating credentials.AADSTS70008: The provided access grant is expired or revoked.Trace ID: f7ec686c-9196-4220-a754-cd9197de44e9Correlation ID: 04bb0cae-580b-49ac-9a10-b6c3316b1eaaTimestamp: 2015-09-16 07:24:55Z\",\"error_codes\":[70002,70008],\"timestamp\":\"2015-09-16 07:24:55Z\",\"trace_id\":\"f7ec686c-9196-4220-a754-cd9197de44e9\",\"correlation_id\":\"04bb0cae-580b-49ac-9a10-b6c3316b1eaa\"}");
responseMessage.Content = content;
return responseMessage;
}
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:MockHelpers.cs
示例5: AddToFavorite
public async Task<bool> AddToFavorite(Recipe r)
{
try
{
string json = JsonConvert.SerializeObject(r);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("api/recipes", content);
if ((response.IsSuccessStatusCode) || (response.StatusCode.ToString().Equals("Conflict")))
{
String recipeId = r.recipe_id + currentApp.GlobalInstance.userId;
UserFavorite uFav = new UserFavorite(recipeId, currentApp.GlobalInstance.userId, r.recipe_id);
string jsonfav = JsonConvert.SerializeObject(uFav);
HttpContent contentfav = new StringContent(jsonfav, Encoding.UTF8, "application/json");
HttpResponseMessage responsefav = await client.PostAsync("api/userfavorites", contentfav);
if (responsefav.IsSuccessStatusCode)
{
return true;
}
return false;
}
}
catch (HttpRequestException e) {
return false;
}
return false;
}
开发者ID:Nevichi,项目名称:BonappFinal,代码行数:27,代码来源:AzureDataAccess.cs
示例6: Controller_Can_POST_a_new_Registerd_User
// ReSharper disable once InconsistentNaming
public async void Controller_Can_POST_a_new_Registerd_User()
{
using (var client = new HttpClient())
{
// Arrange
client.BaseAddress = new Uri(UrlBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Manually set "content-type" header to reflect serialized data format.
var settings = new JsonSerializerSettings();
var ser = JsonSerializer.Create(settings);
var j = JObject.FromObject(_registration, ser);
HttpContent content = new StringContent(j.ToString());
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Act
// PostAsJsonAsync(), per MS recommendation, however results in problem of RegisterAsync() accepting payload: content type?
// Serialized registration data is now associated with HttpContent element explicitly, with format then set.
var response = await client.PostAsync(client.BaseAddress + "/RegisterAsync", content);
//var response = await client.PostAsJsonAsync(client.BaseAddress + "/RegisterAsync", _registration); // error
// Assert
Assert.IsTrue(response.StatusCode == HttpStatusCode.Created);
Assert.IsTrue(response.IsSuccessStatusCode);
}
}
开发者ID:RichardPAsch,项目名称:PIMS,代码行数:31,代码来源:VerifyAuthentication.cs
示例7: AppBarButton_Click
private async void AppBarButton_Click(object sender, RoutedEventArgs e)
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(ip);
models.Autenticacao a = new models.Autenticacao
{
Login = login.Text,
Senha = senha.Text
};
string s = "=" + JsonConvert.SerializeObject(a);
var content = new StringContent(s, Encoding.UTF8,
"application/x-www-form-urlencoded");
var response = await httpClient.PostAsync("/api/user/login", content);
var str = response.Content.ReadAsStringAsync().Result;
str = "OK";
if (str == "OK")
{
this.Frame.Navigate(typeof(MainPage));
}
}
开发者ID:Bonei,项目名称:adedonha,代码行数:26,代码来源:Login.xaml.cs
示例8: GetHighwaveProduct
public async Task<OperationResult<PageResult<product>>> GetHighwaveProduct(string accessToken, string[] brands, DateTime start, DateTime? end = null, int pageIndex = 1, int pageSize = 20)
{
string requestUrl = string.Format(url + @"/highwave/GetProduct?pageIndex={0}&pageSize={1}", pageIndex, pageSize);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorizationScheam, accessToken);
var postString = new StringContent(JsonConvert.SerializeObject(new { brands = brands, start = start, end = end }));
postString.Headers.ContentType.MediaType = contentType;
var result = await client.PostAsync(requestUrl, postString);
if (result.StatusCode != HttpStatusCode.OK)
{
var errorStr = await result.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<OperationResult>(errorStr);
return new OperationResult<PageResult<Models.product>>() { err_code = error.err_code, err_info = error.err_info };
}
var Json = result.Content.ReadAsStringAsync().Result;
PageResult<product> product = JsonConvert.DeserializeObject<PageResult<product>>(Json);
return new OperationResult<PageResult<product>>() { err_code = ErrorEnum.success, err_info = ErrorEnum.success.ToString(), entity = product };
}
开发者ID:ncqingchuan,项目名称:Hyde,代码行数:27,代码来源:HighwaveOp.cs
示例9: SendBuffer
/// <summary>
/// Send events to Seq.
/// </summary>
/// <param name="events">The buffered events to send.</param>
protected override void SendBuffer(LoggingEvent[] events)
{
if (ServerUrl == null)
return;
var payload = new StringWriter();
payload.Write("{\"events\":[");
LoggingEventFormatter.ToJson(events, payload);
payload.Write("]}");
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
if (!string.IsNullOrWhiteSpace(ApiKey))
content.Headers.Add(ApiKeyHeaderName, ApiKey);
var baseUri = ServerUrl;
if (!baseUri.EndsWith("/"))
baseUri += "/";
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUri) })
{
var result = httpClient.PostAsync(BulkUploadResource, content).Result;
if (!result.IsSuccessStatusCode)
ErrorHandler.Error(string.Format("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result));
}
}
开发者ID:jasminsehic,项目名称:seq-client,代码行数:29,代码来源:SeqAppender.cs
示例10: MakeResourcePutRequest
private static string MakeResourcePutRequest(string resourceName)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(BridgeBaseAddress);
var content = new StringContent(
string.Format(@"{{ name : ""{0}"" }}", resourceName),
Encoding.UTF8,
"application/json");
try
{
var response = httpClient.PutAsync("/resource/", content).Result;
if (!response.IsSuccessStatusCode)
throw new Exception("Unexpected status code: " + response.StatusCode);
var responseContent = response.Content.ReadAsStringAsync().Result;
var match = regexResource.Match(responseContent);
if (!match.Success || match.Groups.Count != 2)
throw new Exception("Invalid response from bridge: " + responseContent);
return match.Groups[1].Value;
}
catch (Exception exc)
{
throw new Exception("Unable to start resource: " + resourceName, exc);
}
}
}
开发者ID:Ln1052,项目名称:wcf,代码行数:28,代码来源:BridgeClient.cs
示例11: MakeConfigRequest
private static void MakeConfigRequest()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(BridgeBaseAddress);
var content = new StringContent(
CreateConfigRequestContentAsJson(),
Encoding.UTF8,
"application/json");
try
{
var response = httpClient.PostAsync("/config/", content).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
string reason = String.Format("{0}Bridge returned unexpected status code='{1}', reason='{2}'",
Environment.NewLine, response.StatusCode, response.ReasonPhrase);
if (response.Content != null)
{
string contentAsString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
reason = String.Format("{0}, content:{1}{2}",
reason, Environment.NewLine, contentAsString);
}
throw new Exception(reason);
}
_BridgeStatus = BridgeState.Started;
}
catch (Exception exc)
{
_BridgeStatus = BridgeState.Faulted;
throw new Exception("Bridge is not running", exc);
}
}
}
开发者ID:MarcosRamiro,项目名称:wcf,代码行数:33,代码来源:BridgeClient.cs
示例12: MakeConfigRequest
private static void MakeConfigRequest()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(BridgeBaseAddress);
string resourceFolder = TestProperties.GetProperty(TestProperties.BridgeResourceFolder_PropertyName);
string contentPayload = "{ resourcesDirectory : \"" + resourceFolder + "\" }";
var content = new StringContent(
contentPayload,
Encoding.UTF8,
"application/json");
try
{
var response = httpClient.PostAsync("/config/", content).Result;
if (!response.IsSuccessStatusCode)
throw new Exception("Unexpected status code: " + response.StatusCode);
_BridgeStatus = BridgeState.Started;
}
catch (Exception exc)
{
_BridgeStatus = BridgeState.Faulted;
throw new Exception("Bridge is not running", exc);
}
}
}
开发者ID:Ln1052,项目名称:wcf,代码行数:25,代码来源:BridgeClient.cs
示例13: ProcessBatchAsync_CallsRegisterForDispose
public void ProcessBatchAsync_CallsRegisterForDispose()
{
List<IDisposable> expectedResourcesForDisposal = new List<IDisposable>();
MockHttpServer server = new MockHttpServer(request =>
{
var tmpContent = new StringContent(String.Empty);
request.RegisterForDispose(tmpContent);
expectedResourcesForDisposal.Add(tmpContent);
return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) };
});
UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
{
Content = new MultipartContent("mixed")
{
ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
new MultipartContent("mixed") // ChangeSet
{
ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/"))
}
}
};
var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result;
var resourcesForDisposal = batchRequest.GetResourcesForDisposal();
foreach (var expectedResource in expectedResourcesForDisposal)
{
Assert.Contains(expectedResource, resourcesForDisposal);
}
}
开发者ID:balajivasudevan,项目名称:aspnetwebstack,代码行数:31,代码来源:UnbufferedODataBatchHandlerTest.cs
示例14: SetRequestSerailizedContent
/// <summary>
/// Sets the content of the request by the given body and the the required GZip configuration.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="service">The service.</param>
/// <param name="body">The body of the future request. If <c>null</c> do nothing.</param>
/// <param name="gzipEnabled">
/// Indicates if the content will be wrapped in a GZip stream, or a regular string stream will be used.
/// </param>
internal static void SetRequestSerailizedContent(this HttpRequestMessage request,
IClientService service, object body, bool gzipEnabled)
{
if (body == null)
{
return;
}
HttpContent content = null;
var mediaType = "application/" + service.Serializer.Format;
var serializedObject = service.SerializeObject(body);
if (gzipEnabled)
{
content = CreateZipContent(serializedObject);
content.Headers.ContentType = new MediaTypeHeaderValue(mediaType)
{
CharSet = Encoding.UTF8.WebName
};
}
else
{
content = new StringContent(serializedObject, Encoding.UTF8, mediaType);
}
request.Content = content;
}
开发者ID:Inspirony,项目名称:Emby.Plugins,代码行数:35,代码来源:HttpRequestMessageExtenstions.cs
示例15: WriteMessageAsync_WritesResponseMessage
public void WriteMessageAsync_WritesResponseMessage()
{
MemoryStream ms = new MemoryStream();
HttpContent content = new StringContent(String.Empty, Encoding.UTF8, "multipart/mixed");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", Guid.NewGuid().ToString()));
IODataResponseMessage odataResponse = new ODataMessageWrapper(ms, content.Headers);
var batchWriter = new ODataMessageWriter(odataResponse).CreateODataBatchWriter();
HttpResponseMessage response = new HttpResponseMessage()
{
Content = new StringContent("example content", Encoding.UTF8, "text/example")
};
response.Headers.Add("customHeader", "bar");
batchWriter.WriteStartBatch();
ODataBatchResponseItem.WriteMessageAsync(batchWriter, response).Wait();
batchWriter.WriteEndBatch();
ms.Position = 0;
string result = new StreamReader(ms).ReadToEnd();
Assert.Contains("example content", result);
Assert.Contains("text/example", result);
Assert.Contains("customHeader", result);
Assert.Contains("bar", result);
}
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:25,代码来源:ODataBatchResponseItemTest.cs
示例16: PutGitHubFileAsync
public async Task PutGitHubFileAsync(
string fileUrl,
string commitMessage,
string newFileContents)
{
Trace.TraceInformation($"Getting the 'sha' of the current contents of file '{fileUrl}'");
string currentFile = await _httpClient.GetStringAsync(fileUrl);
string currentSha = JObject.Parse(currentFile)["sha"].ToString();
Trace.TraceInformation($"Got 'sha' value of '{currentSha}'");
Trace.TraceInformation($"Request to update file '{fileUrl}' contents to:");
Trace.TraceInformation(newFileContents);
string updateFileBody = JsonConvert.SerializeObject(new
{
message = commitMessage,
committer = new
{
name = _auth.User,
email = _auth.Email
},
content = ToBase64(newFileContents),
sha = currentSha
}, Formatting.Indented);
var bodyContent = new StringContent(updateFileBody);
using (HttpResponseMessage response = await _httpClient.PutAsync(fileUrl, bodyContent))
{
response.EnsureSuccessStatusCode();
Trace.TraceInformation("Updated the file successfully.");
}
}
开发者ID:ChadNedzlek,项目名称:buildtools,代码行数:34,代码来源:GitHubClient.cs
示例17: CreateEvent
public void CreateEvent(Guid eventId, string eventType = "DetailsView")
{
var @event = new
{
EventId = eventId,
Timestamp = DateTimeFactory.Now().ToString("O"),
EventType = eventType
};
var eventJson = JsonConvert.SerializeObject(@event, _jsonSettings);
var requestContent = new StringContent(eventJson, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "/events") { Content = requestContent };
var response = _httpClient.SendAsync(request);
try
{
var result = response.Result;
var statusCode = result.StatusCode;
if (statusCode == HttpStatusCode.Created)
{
return;
}
RaiseResponseError(request, result);
}
finally
{
Dispose(request, response);
}
}
开发者ID:allansson,项目名称:pact-net,代码行数:31,代码来源:EventsApiClient.cs
示例18: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
return await Task.Run(() =>
{
var metadata = _metadataProvider.GetMetadata(request);
if (request.Headers.Any(h => h.Key == "X-Proxy-Type" && h.Value.Contains("metadata")))
return request.CreateResponse(System.Net.HttpStatusCode.OK, metadata);
var template = new JsProxyTemplate(metadata);
var js = new StringContent(template.TransformText());
js.Headers.ContentType = new MediaTypeHeaderValue("application/javascript");
return new HttpResponseMessage { Content = js }; ;
});
}
开发者ID:philemn,项目名称:WebApiProxy,代码行数:28,代码来源:ProxyHandler.cs
示例19: SendSampleData
private static void SendSampleData()
{
try {
var sampleData = new
{
value = "Sending some test info" + DateTime.Now.ToString()
};
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = string.Format("Sending data on {0}", DateTime.Now.ToLongTimeString());
var jsonData = string.Format("{{'sender': '{0}', 'message': '{1}' }}", Environment.MachineName, data);
var stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = httpClient.PostAsync(ConfigurationManager.AppSettings["serverAdress"] + "/api/data", stringContent).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Post succesful, StatusCode: " + response.StatusCode);
}
else
{
Console.WriteLine("Post failed, StatusCode: " + response.StatusCode);
}
}
catch (Exception ex)
{
Console.Write(ex.Message + ex.StackTrace);
}
}
开发者ID:tsankohristov,项目名称:RPISimpleCommunication,代码行数:35,代码来源:Program.cs
示例20: Authenticate
public void Authenticate()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(webServiceRootPath);
var content = new StringContent(
string.Format("grant_type=password&username={0}&password={1}", login.Replace("@", "%40"), password),
Encoding.UTF8,
"text/plain");
client.Timeout = TimeSpan.FromSeconds(30);
var response = client.PostAsync("Token", content).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Authentication failed " + FormatHttpError(response));
}
string serialized = response.Content.ReadAsStringAsync().Result;
var model = JsonConvert.DeserializeObject<TokenResponseModel>(serialized);
if (!"bearer".Equals(model.TokenType, StringComparison.InvariantCultureIgnoreCase))
{
throw new Exception("Returned token is not of bearer type, actual: " + model.TokenType);
}
token = model.AccessToken;
}
}
开发者ID:imtheman,项目名称:WurmAssistant3,代码行数:25,代码来源:PublishingWebService.cs
注:本文中的System.Net.Http.StringContent类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论