本文整理汇总了C#中System.Net.Http.HttpClient.PutAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.PutAsync方法的具体用法?C# HttpClient.PutAsync怎么用?C# HttpClient.PutAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClient
的用法示例。
在下文中一共展示了HttpClient.PutAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendEmployee
private static async Task SendEmployee(Employee employee, string dataFormat, int portNumber)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("DataUpdatePort", portNumber.ToString());
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", dataFormat);
// Construct the request.
string url = "http://localhost:8080/employee/";
HttpResponseMessage response = null;
if (dataFormat == "application/xml")
{
response = await httpClient.PutAsync(url, employee, new XmlMediaTypeFormatter() { UseXmlSerializer = true});
}
else if (dataFormat == "application/json")
{
response = await httpClient.PutAsync(url, employee, new JsonMediaTypeFormatter());
}
if (response.IsSuccessStatusCode)
{
Console.WriteLine(@"Employee with ID = " + employee.EmployeeId + "was sent to the DataWarehouse.");
}
else
{
Console.WriteLine(@"Warning: Unable to send employee with ID = " + employee.EmployeeId + " to the DataWarehouse.");
}
}
}
示例2: AlbumsControllerTest
private static async Task AlbumsControllerTest(HttpClient client)
{
// create album
await client.PostAsync("Albums/Create",
new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 009") }));
await client.PostAsync("Albums/Create",
new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 010") }));
// get all albums
Console.WriteLine(await client.GetStringAsync("Albums/All"));
// update album
await client.PutAsync("Albums/Update",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", "2"),
new KeyValuePair<string, string>("year", "2014"),
new KeyValuePair<string, string>("producer", "gosho ot pochivka")
}));
// delete album
await client.DeleteAsync("Albums/Delete/1");
// add song to album
await client.PutAsync("Albums/AddSong?albumId=2&songId=2", null);
// add artist to album
await client.PutAsync("Albums/AddArtist?albumId=2&artistId=2", null);
}
示例3: OnNavigatedTo
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Game game = (Game) e.Parameter;
TimeSpan timeSpan = (game.FinishedAt - game.StartedAt);
string timespanString = timeSpan.Days + "d " + timeSpan.Hours + "h " + timeSpan.Minutes + "m " + timeSpan.Seconds + "s";
timeTextBlock.Text += " " + timespanString;
string[] difficulties = { "Normal", "Hard", "Insane" };
difficultyTextBlock.Text += " " + difficulties[game.Difficulty];
using (var client = new HttpClient())
{
var content = JsonConvert.SerializeObject(game);
// Send a POST
Task task = Task.Run(async () =>
{
var request = new StringContent(content, Encoding.UTF8, "application/json");
await client.PutAsync(App.BaseUri + "games", request);
});
task.Wait();
}
// Back button
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}
示例4: Main
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://ncs-sz-jinnan:3721");
HttpClient httpClient = new HttpClient { BaseAddress = baseAddress };
IEnumerable<Contact> contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
Console.WriteLine("当前联系人列表");
ListContacts(contacts);
Contact contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "789" };
Console.WriteLine("\n添加联系人003");
httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "987" };
Console.WriteLine("\n修改联系人003");
httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
Console.WriteLine("\n删除联系人003");
httpClient.DeleteAsync("/api/contacts/003").Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
Console.Read();
}
示例5: GetResponseAsync
public async Task<HttpResponseMessage> GetResponseAsync(RestCommand command, string data = "")
{
try
{
using (var handler = new HttpClientHandler())
{
if (_credentials != null)
handler.Credentials = _credentials;
using (var httpClient = new HttpClient(handler))
{
ConfigureHttpClient(httpClient);
switch (command.HttpMethod)
{
case HttpMethod.Get:
return await httpClient.GetAsync(command.FullResourceUri);
case HttpMethod.Put:
return await httpClient.PutAsync(command.FullResourceUri, new StringContent(data));
case HttpMethod.Post:
return await httpClient.PostAsync(command.FullResourceUri, new StringContent(data));
case HttpMethod.Delete:
return await httpClient.DeleteAsync(command.FullResourceUri);
}
throw new Exception(string.Format("The command '{0}' does not have a valid HttpMethod. (Type: {1})", command, command.GetType().FullName));
}
}
}
catch (Exception e)
{
throw new Exception("An error occured while performing the request.", e);
}
}
示例6: CallAzureResourceManagerApi
private static async Task CallAzureResourceManagerApi(string resourceManagementEndpoint, string subscriptionId, string header, string resourceGroupName)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", header);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
//register the subscription with DataFactory provider
StringContent body = new StringContent("", Encoding.UTF8, "application/json");
string endpoint = "{0}subscriptions/{1}/providers/Microsoft.DataFactory/register?api-version=2015-01-01";
string uri = String.Format(endpoint, resourceManagementEndpoint, subscriptionId);
HttpResponseMessage resp = await client.PostAsync(uri, body);
Console.WriteLine("registration status: {0}", resp.StatusCode);
// Resource Group API
//StringContent body = new StringContent("{\"location\":\"West US\",\"tags\":{}}", Encoding.UTF8, "application/json");
//string endpoint = "{0}subscriptions/{1}/resourcegroups/{2}?api-version=2014-04-01";
// ADF REST API
body = new StringContent("{\"location\":\"West US\",\"tags\":{}}", Encoding.UTF8, "application/json");
endpoint = "{0}subscriptions/{1}/resourcegroups/{2}/providers/Microsoft.DataFactory/datafactories/{3}?api-version=2014-10-01-preview";
uri = String.Format(endpoint, resourceManagementEndpoint, subscriptionId, resourceGroupName, dataFactoryName);
resp = await client.PutAsync(uri, body);
Console.WriteLine("creation status: {0}", resp.StatusCode);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
示例7: LeaveAnEvent
private async void LeaveAnEvent()
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", this.parent.Bearer));
var raw = new List<KeyValuePair<string, string>>
{
};
var content = new FormUrlEncodedContent(raw);
string link = this.URI_JOIN_LEAVE.ToString() + "leave/" + this.numericId.Value;
using (var response = await client.PutAsync(link, content))
{
if (response.IsSuccessStatusCode)
{
MessageBox.Show("The event was left.");
}
else
{
MessageBox.Show(response.ReasonPhrase, "Error");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
示例8: DoSyncRequest
public ElasticsearchResponse DoSyncRequest(string method, Uri uri, byte[] data = null)
{
var client = new System.Net.Http.HttpClient();
HttpResponseMessage response = null;
byte[] result = null;
HttpContent content = null;
if (data != null)
content = new ByteArrayContent(data);
switch (method.ToLower())
{
case "head":
response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri) ).Result;
result = response.Content.ReadAsByteArrayAsync().Result;
break;
case "delete":
response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri) { Content = content }).Result;
result = response.Content.ReadAsByteArrayAsync().Result;
break;
case "put":
response = client.PutAsync(uri, content).Result;
result = response.Content.ReadAsByteArrayAsync().Result;
break;
case "post":
response = client.PostAsync(uri, content).Result;
result = response.Content.ReadAsByteArrayAsync().Result;
break;
case "get":
response = client.GetAsync(uri).Result;
result = response.Content.ReadAsByteArrayAsync().Result;
break;
}
return ElasticsearchResponse.Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result);
}
示例9: OnTimedEvent
async private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
switch (effectMode) {
case "test":
TestPut();
break;
case "ambient":
AmbientPut();
break;
case "daylight":
DaylightPut();
break;
}
try {
HttpClient client = new HttpClient();
StringContent content = new StringContent(JsonParser.Serialize(bufferData), Encoding.UTF8);
if (effectsOn) {
await client.PutAsync(lightArray[lastLight], content);
}
} catch (Exception) { return; } finally {
lastLight++;
if (lastLight >= lightArray.Length) {
lastLight = 0;
}
}
}
示例10: CreateServerAsync
private static async Task CreateServerAsync()
{
var httpClient = new HttpClient();
var serverConfiguration = new ServerConfiguration
{
DefaultStorageTypeName = "voron",
Port = Port,
RunInMemory = true,
Settings =
{
{ "Raven/ServerName", ServerName }
}
};
var response = await httpClient
.PutAsync("http://localhost:8585/servers", new JsonContent(RavenJObject.FromObject(serverConfiguration)))
.ConfigureAwait(false);
if (response.IsSuccessStatusCode == false)
throw new InvalidOperationException("Failed to start server.");
using (var stream = await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false))
{
var data = RavenJToken.TryLoad(stream);
if (data == null)
throw new InvalidOperationException("Failed to retrieve server url.");
ServerUrl = data.Value<string>("ServerUrl");
}
}
示例11: Button_Click_1
private async void Button_Click_1(object sender, RoutedEventArgs e) {
var car = (Car)DataContext;
using (HttpClient httpClient = new HttpClient()) {
var jsonContent = new StringContent(
await JsonConvert.SerializeObjectAsync(car)
);
jsonContent.Headers.ContentType.MediaType = "application/json";
var response = await httpClient.PutAsync(
Constants.BASE_API_ADDRESS, jsonContent
);
try {
response.EnsureSuccessStatusCode();
} catch (Exception ex) {
MessageBox.Show(
string.Format(
"The request was not successful. Message: {0}", ex.Message
)
);
} finally {
this.Close();
}
}
}
示例12: Get
public async System.Threading.Tasks.Task<HttpResponseMessage> Get(string url, string body, string contenttype)
{
using (var client = new HttpClient())
{
return await client.PutAsync(url, new StringContent(body, System.Text.Encoding.UTF8, contenttype));
}
}
示例13: LightOnTask
public async Task<string> LightOnTask(Boolean on, int Id)
{
this.on = on;
string url = "http://" + ip + ":" + port + "/" + "api/" + username + "/" + "lights" + "/" + Id + "/" + "state";
HttpContent content;
if (on == true)
{
content = new StringContent
("{\"on\": true }",
Encoding.UTF8,
"application/json");
}
else {
content = new StringContent
("{\"on\": false}",
Encoding.UTF8,
"application/json");
}
using (HttpClient hc = new HttpClient())
{
var response = await hc.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
示例14: Send
private string Send(FileTransmission transmission, string basePath = null)
{
var path = basePath == null
? Path.GetFileName(transmission.Path)
: transmission.Path.Replace(basePath, string.Empty);
var uri = new Uri ("{0}/warpgate/io/{1}".Fmt(transmission.BaseUrl, path));
using (var file = File.OpenRead (transmission.Path)) {
var content = new StreamContent (file);
using (var client = new HttpClient ()) {
var upload = client.PutAsync (uri, content);
upload.Wait ();
var readContent = upload.Result.Content.ReadAsStringAsync ();
readContent.Wait ();
return readContent.Result;
}
}
}
示例15: PutData
public async Task<Result> PutData(Uri uri, StringContent json, UserAccountEntity userAccountEntity)
{
var httpClient = new HttpClient();
try
{
var authenticationManager = new AuthenticationManager();
if (userAccountEntity.GetAccessToken().Equals("refresh"))
{
await authenticationManager.RefreshAccessToken(userAccountEntity);
}
var user = userAccountEntity.GetUserEntity();
if (user != null)
{
var language = userAccountEntity.GetUserEntity().Language;
httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
}
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
var response = await httpClient.PutAsync(uri, json);
var responseContent = await response.Content.ReadAsStringAsync();
return response.IsSuccessStatusCode ? new Result(true, string.Empty) : new Result(false, responseContent);
}
catch (Exception)
{
return new Result(false, string.Empty);
}
}