本文整理汇总了C#中HttpClient.PutAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.PutAsync方法的具体用法?C# HttpClient.PutAsync怎么用?C# HttpClient.PutAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpClient
的用法示例。
在下文中一共展示了HttpClient.PutAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PutJsonAsync
public async Task<string> PutJsonAsync(string url, IHttpContent content, string token = null)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders
.Accept
.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
if (token != null)
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
}
HttpResponseMessage response = await client.PutAsync(new Uri(BaseUrl + url), content);
string result = await response.Content.ReadAsStringAsync();
return result;
}
示例2: LightColorTask
private static async Task<string> LightColorTask(int hue, int sat, int bri, int Id)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
HttpStringContent content
= new HttpStringContent
($"{{ \"bri\": {bri} , \"hue\": {hue} , \"sat\": {sat}}}",
Windows.Storage.Streams.UnicodeEncoding.Utf8,
"application/json");
//MainPage.RetrieveSettings(out ip, out port, out username);
Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state");
var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
return string.Empty;
}
string jsonResponse = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(jsonResponse);
return jsonResponse;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return string.Empty;
}
}
示例3: RemoveShoppingCartItemAsync
public async Task RemoveShoppingCartItemAsync(string shoppingCartId, string itemIdToRemove)
{
using (var shoppingCartClient = new HttpClient())
{
string requestUrl = _shoppingCartBaseUrl + shoppingCartId + "?itemIdToRemove=" + itemIdToRemove;
var response = await shoppingCartClient.PutAsync(new Uri(requestUrl), null);
response.EnsureSuccessStatusCode();
}
}
示例4: apiPUT
public async Task<bool> apiPUT(string access_token, string response, string href)
{
mlibrary = new methodLibrary();
HttpClient httpClient = new HttpClient();
try
{
httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);
httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
var httpResponseMessage = await httpClient.PutAsync(new Uri(href), new HttpStringContent(response));
string resp = await httpResponseMessage.Content.ReadAsStringAsync();
await mlibrary.writeFile("PUTresponse", resp);
Debug.WriteLine(resp);
ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;
}
catch (Exception ex)
{
Debug.WriteLine("Caught exception : " + ex);
return false;
}
return true;
}
示例5: LightOnTask
private static async Task<string> LightOnTask(Boolean on, int Id)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
HttpStringContent content
= new HttpStringContent
($"{{ \"on\": {on} }}",
Windows.Storage.Streams.UnicodeEncoding.Utf8,
"application/json");
Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state");
var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
return string.Empty;
}
string jsonResponse = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(jsonResponse);
return jsonResponse;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return string.Empty;
}
}
示例6: Put
private async Task<String> Put(string path, string json)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json");
Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);
var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
return string.Empty;
}
string jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return string.Empty;
}
}
示例7: GetFromWebWinPhone
/// <summary>
/// Executes a HTTP request for Windows phone based device
/// </summary>
/// <param name="body">body of the request</param>
/// <returns>Array of bytes</returns>
private async Task<byte[]> GetFromWebWinPhone(byte[] body)
{
HttpClient request = new HttpClient();
Uri connectionUri = new Uri(_url);
HttpFormUrlEncodedContent formContent = null;
if (body != null && body.Length > 0)
formContent = new HttpFormUrlEncodedContent(_body);
HttpResponseMessage response = null;
if (_method.Equals(AsyncRequest.Get))
response = await request.GetAsync(connectionUri);
if (_method.Equals(AsyncRequest.Post))
response = await request.PostAsync(connectionUri, formContent);
if (_method.Equals(AsyncRequest.Put))
response = await request.PutAsync(connectionUri, formContent);
if (_method.Equals(AsyncRequest.Delete))
response = await request.DeleteAsync(connectionUri);
IBuffer stream = await response.Content.ReadAsBufferAsync();
byte[] readstream = new byte[stream.Length];
using (var reader = DataReader.FromBuffer(stream))
reader.ReadBytes(readstream);
request.Dispose();
response.Dispose();
return readstream;
}
示例8: PutMessage
//send lights info
public async void PutMessage(HttpStringContent content, Uri uri)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
var response = await client.PutAsync(uri, content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
Online = false;
Debug.WriteLine("niet gelukt");
}
Online = true;
}
catch (Exception e)
{
Online = false;
Debug.WriteLine(e.Message);
}
}
示例9: LightLoopTask
public static async Task<string> LightLoopTask(Light light)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
HttpStringContent content = new HttpStringContent(string.Format("{{ \"effect\": \"{0}\" }}", light.effect == Light.Effect.EFFECT_COLORLOOP ? "colorloop" : "none"), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
string ip, username;
int port;
SettingsService.RetrieveSettings(out ip, out port, out username);
var response = await client.PutAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/lights/{3}/state", ip, port, username, light.id)), content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
return string.Empty;
}
string jsonResponse = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(jsonResponse);
return jsonResponse;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return string.Empty;
}
}
示例10: getConnection
private async Task<HttpResponseMessage> getConnection(String urlFragment, String method, String body)
{
try
{
Uri url = new Uri(String.Format("{0}{1}", serviceUrl, urlFragment));
HttpClient connection = new HttpClient();
var headers = connection.DefaultRequestHeaders;
if (credentialsProvider.GetPassword() != null)
{
headers.Add("Authorization", getAuthorizationHeader());
}
if (userAgent != null)
{
headers.Add("X-Signal-Agent", userAgent);
}
HttpStringContent content;
if (body != null)
{
content = new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
Debug.WriteLine(body);
}
else
{
content = new HttpStringContent("");
}
switch (method)
{
case "POST":
return await connection.PostAsync(url, content);
case "PUT":
return await connection.PutAsync(url, content);
case "DELETE":
return await connection.DeleteAsync(url);
case "GET":
return await connection.GetAsync(url);
default:
throw new Exception("Unknown method: " + method);
}
}
catch (UriFormatException e)
{
throw new Exception(string.Format("Uri {0} {1} is wrong", serviceUrl, urlFragment));
}
catch (Exception e)
{
Debug.WriteLine(string.Format("Other exception {0}{1} is wrong", serviceUrl, urlFragment));
throw new PushNetworkException(e);
}
}
示例11: GroupColorTask
public static async Task<string> GroupColorTask(Light light)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
HttpStringContent content = new HttpStringContent(string.Format("{{ \"hue\": {0}, \"sat\": {1}, \"bri\": {2} }}", light.hue, light.saturation, light.value), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
string ip, username;
int port;
SettingsService.RetrieveSettings(out ip, out port, out username);
var response = await client.PutAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/groups/{3}/action", ip, port, username, light.id)), content).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
return string.Empty;
}
string jsonResponse = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(jsonResponse);
return jsonResponse;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return string.Empty;
}
}
示例12: SendPutRequest
static public async Task<string> SendPutRequest ( object data , string address )
{
string json = JsonConvert.SerializeObject ( data );
//string tokenJson = JsonConvert.SerializeObject ( UserData.token );
//create dictionary
var dict = new Dictionary<string , string> ();
dict["data"] = json;
var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
httpFilter.CacheControl.ReadBehavior =
Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
httpClient = new HttpClient ( httpFilter );
response = new HttpResponseMessage ();
string responseText = "";
//check address
Uri resourceUri;
if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
{
return "Invalid URI, please re-enter a valid URI";
}
if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
{
return "Only 'http' and 'https' schemes supported. Please re-enter URI";
}
//post
try
{
response = await httpClient.PutAsync ( resourceUri , new HttpFormUrlEncodedContent ( dict ) );
response.EnsureSuccessStatusCode ();
responseText = await response.Content.ReadAsStringAsync ();
}
catch ( Exception ex )
{
// Need to convert int HResult to hex string
responseText = "Error = " + ex.HResult.ToString ( "X" ) + " Message: " + ex.Message;
}
httpClient.Dispose ();
return responseText;
}
示例13: ProcessOrderAsync
public async Task ProcessOrderAsync(Order order)
{
using (var orderClient = new HttpClient())
{
orderClient.DefaultRequestHeaders.Add("Accept", "application/json");
// In order to meet the Windows 8 app certification requirements,
// you cannot send Credit Card information to a Service in the clear.
// The payment processing must meet the current PCI Data Security Standard (PCI DSS).
// See http://go.microsoft.com/fwlink/?LinkID=288837
// and http://go.microsoft.com/fwlink/?LinkID=288839
// for more information.
// Replace sensitive information with dummy values
var orderToSend = new Order()
{
Id = order.Id,
UserId = order.UserId,
ShippingMethod = order.ShippingMethod,
ShoppingCart = order.ShoppingCart,
BillingAddress = order.BillingAddress,
ShippingAddress = order.ShippingAddress,
PaymentMethod = new PaymentMethod()
{
CardNumber = "**** **** **** ****",
CardVerificationCode = "****",
CardholderName = order.PaymentMethod.CardholderName,
ExpirationMonth = order.PaymentMethod.ExpirationMonth,
ExpirationYear = order.PaymentMethod.ExpirationYear,
Phone = order.PaymentMethod.Phone
}
};
string requestUrl = _clientBaseUrl + orderToSend.Id;
var stringContent = new HttpStringContent(JsonConvert.SerializeObject(orderToSend), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
var response = await orderClient.PutAsync(new Uri(requestUrl), stringContent);
await response.EnsureSuccessWithValidationSupportAsync();
}
}
示例14: OnNavigatedTo
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
Uri StartUri = new Uri(String.Format(
"https://login.live.com/oauth20_authorize.srf?client_id={0}&scope={1}&response_type=token&redirect_uri={2}",
"000000004812E450",
"wl.signin onedrive.readwrite",
WebUtility.UrlEncode("http://kiewic.com/")));
Uri EndUri = new Uri("http://kiewic.com/");
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
StartUri,
EndUri);
string testData = "http://kiewic.com/#access_token=EwCQAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAASu2H0Plv73qlsNgaAsNtK931pWT/wMdIa4zJzNKDNz9Er%2b97p7qo0XGR4%2bkfr%2bTCh4EV5wQ5NTYHufWeIdlvlm9lkdt3S6SotwygCJtUJqoVBI4fGJxXdTz6tCiqsC2NbZNxGR9od4osWN33ZuNIHp2f3%2b0KiX0fs%2bLJK8wIHW22LtUsj%2bCZY/K9qA%2bEbxAfgIpZDsAzV2U1NdjUobSKkvA3SEaARx/exIm0jZTRvM0XRoNHn/ZhlcMrd1nehEpOM3SFp3%2bkIfKiFiHXVm0P/vRS/VJFHXyNyCDFqGuw63vOklnqT4w2LhQyGu3G/%2bUIJBpBfuSHNwikthHPm3xjYoDZgAACO1iT9UawnDVYAFVZk/mv7wwb58vrJc1l0v7UClfth7j5bm/%2b7yYB0Rr9WHdquSqrotvovjR//V2Kmtgn3rzLQYg8ma5/2t6VgtyPIwbQm6kRP382CYpS3n5ZdvyX7nNWHwM9RlsKkZdS9zT7kkwxVsbW7MJaqSlcnbnkWaad84KzfrjSyxr9ceUb/eajRu3ltRy9Tbtkt2A8QjXtKw2Th82WjIrZjDg10JoeRqvFtfu1IeEBlofUgAPUK7VkbDdKVbgDIl97TZD5qW9m8JTQkhlbq6%2btZhiqFN/JZLOPum6a4sEOAf46v1sw70UDv0raxewMA6y2j6gGMGFojFse6vWHXTLQRpqnBwpc3iOnaaqcMGGCRimdMhtCmKITW9%2bJ/NbKo8DbTk65ancQYmBgNpNHNVStZTGex3MwcxEY9mQ1p69aXN0fXhWY7GL%2bB0wEuwJn50H04s4WtlepIv2Ww0QhfZ1vxkd1HIRdwE%3d&authentication_token=eyJhbGciOiJIUzI1NiIsImtpZCI6IjEiLCJ0eXAiOiJKV1QifQ.eyJ2ZXIiOjEsImlzcyI6InVybjp3aW5kb3dzOmxpdmVpZCIsImV4cCI6MTQyNTYxMjU0NCwidWlkIjoiNmM0NzY5YjcxMmZlNDBjYTY0MDAyYTg4MDI1NjBkMjgiLCJhdWQiOiJraWV3aWMuY29tIiwidXJuOm1pY3Jvc29mdDphcHB1cmkiOiJhcHBpZDovLzAwMDAwMDAwNDgxMkU0NTAiLCJ1cm46bWljcm9zb2Z0OmFwcGlkIjoiMDAwMDAwMDA0ODEyRTQ1MCJ9.Xzw94LXFH3wIwwSWpQmxPH9HAB9H-qyLLW4WZfcSY9o&token_type=bearer&expires_in=3600&scope=wl.signin%20onedrive.readwrite%20wl.basic%20wl.contacts_skydrive%20wl.skydrive%20wl.skydrive_update&user_id=6c4769b712fe40ca64002a8802560d28";
testData = result.ResponseData;
var urlDecoder = new WwwFormUrlDecoder(testData);
foreach (var decoderEntry in urlDecoder)
{
Debug.WriteLine(decoderEntry.Name + " " + decoderEntry.Value);
}
string token = urlDecoder.GetFirstValueByName("http://kiewic.com/#access_token");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", String.Format("bearer {0}", token));
HttpStringContent createSessionContent = new HttpStringContent(
"{ \"@name.conflictBehavior\": \"rename\" }",
UnicodeEncoding.Utf8,
"application/json");
Uri createSessionUri = new Uri("https://api.onedrive.com/v1.0/drive/root:/Foo/bar2.txt:/upload.createSession");
var response = await client.PostAsync(createSessionUri, createSessionContent);
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
JsonObject jsonObject = JsonObject.Parse(responseString);
Uri uploadUrl = new Uri(jsonObject.GetNamedString("uploadUrl"));
HttpStringContent putContent1 = new HttpStringContent(
"hello ",
UnicodeEncoding.Utf8,
"text/plain");
putContent1.Headers.Add("Content-Range", "bytes 0-5/11");
HttpStringContent putContent2 = new HttpStringContent(
"world",
UnicodeEncoding.Utf8,
"text/plain");
putContent2.Headers.Add("Content-Range", "bytes 6-10/11");
response = await client.PutAsync(uploadUrl, putContent2);
responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
response = await client.PutAsync(uploadUrl, putContent1);
responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
}
示例15: HttpPutAsync
/// <summary>
/// Sends a PUT command via HTTP and returns the response.
/// </summary>
internal async Task<string> HttpPutAsync(string commandUrl, string body)
{
using (var client = new HttpClient())
{
Uri uri = new Uri($"http://{UrlBase}{commandUrl}");
HttpResponseMessage response = await client.PutAsync(uri, new HttpStringContent(body));
return await response.Content.ReadAsStringAsync();
}
}