本文整理汇总了C#中HttpRequestMessage类的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage类的具体用法?C# HttpRequestMessage怎么用?C# HttpRequestMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpRequestMessage类属于命名空间,在下文中一共展示了HttpRequestMessage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateToken
private async Task<Boolean> CreateToken(string csrfToken)
{
var request = new HttpRequestMessage(HttpMethod.Post, CommonData.BaseUri + "/session/token");
request.Headers.Add("X-SB1-Rest-Version", "1.0.0");
request.Headers.Add("X-CSRFToken", csrfToken);
request.Content = new StringContent(
JsonConvert.SerializeObject(new { description = "klokkebank" }),
Encoding.UTF8, "application/json");
var response = await Client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
LastError = "Kunne ikke opprette token";
return false;
}
var token = JsonConvert.DeserializeObject<JObject>(await response.Content.ReadAsStringAsync());
Token = (string)token["token"];
SaveSettings();
return true;
}
示例2: HttpPost
public static async void HttpPost(string cid, string cname, string cimage, string cdream, string fid, string fname,string fimage,string fdream)
{
try
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(Config.apiUserFollow));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("cphone", cid),
new KeyValuePair<string, string>("cname", cname),
new KeyValuePair<string, string>("cimage", cimage),
new KeyValuePair<string, string>("cdream", cdream),
new KeyValuePair<string, string>("fphone", fid),
new KeyValuePair<string, string>("fname", fname),
new KeyValuePair<string, string>("fimage", fimage),
new KeyValuePair<string, string>("fdream", fdream),
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例3: Launch_Click
private async void Launch_Click(object sender, RoutedEventArgs e)
{
if (FacebookClientID.Text == "")
{
rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
return;
}
var uri = new Uri("https://graph.facebook.com/me");
HttpClient httpClient = GetAutoPickerHttpClient(FacebookClientID.Text);
DebugPrint("Getting data from facebook....");
var request = new HttpRequestMessage(HttpMethod.Get, uri);
try
{
var response = await httpClient.SendRequestAsync(request);
if (response.IsSuccessStatusCode)
{
string userInfo = await response.Content.ReadAsStringAsync();
DebugPrint(userInfo);
}
else
{
string str = "";
if (response.Content != null)
str = await response.Content.ReadAsStringAsync();
DebugPrint("ERROR: " + response.StatusCode + " " + response.ReasonPhrase + "\r\n" + str);
}
}
catch (Exception ex)
{
DebugPrint("EXCEPTION: " + ex.Message);
}
}
示例4: SetupPushNotificationChannelForApplicationAsync
public async void SetupPushNotificationChannelForApplicationAsync(string token, string arguments)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentException("you should add you app token");
}
//var encryptedArguments = Helper.Encrypt(arguments, "cnblogs", "somesalt");
_channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var content = new HttpFormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("arguments", arguments),
new KeyValuePair<string, string>("token", token),
new KeyValuePair<string, string>("uri", _channel.Uri),
new KeyValuePair<string, string>("uuid", GetUniqueDeviceId())
});
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server));
request.Content = content;
var client = new HttpClient();
var response = await client.SendRequestAsync(request);
_channel.PushNotificationReceived += _channel_PushNotificationReceived;
}
示例5: InvalidateAsync
public async Task InvalidateAsync()
{
EncodeCredentials();
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2InvalidateToken));
req.Headers.Add("Authorization", "Basic " + BasicToken);
req.Headers.Add("User-Agent", UserAgent);
req.Headers.Add("Expect", "100-continue");
req.Content = new HttpStringContent("access_token=" + BearerToken, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var baseFilter = new HttpBaseProtocolFilter
{
AutomaticDecompression = true
};
//var handler = new HttpClientHandler();
//if (handler.SupportsAutomaticDecompression)
// handler.AutomaticDecompression = DecompressionMethods.GZip;
//if (Proxy != null && handler.SupportsProxy)
// handler.Proxy = Proxy;
using (var client = new HttpClient(baseFilter))
{
var msg = await client.SendRequestAsync(req);
await TwitterErrorHandler.ThrowIfErrorAsync(msg);
string response = await msg.Content.ReadAsStringAsync();
var responseJson = JsonMapper.ToObject(response);
BearerToken = responseJson.GetValue<string>("access_token");
}
}
示例6: Constructor_ReportsBytesWritten
public void Constructor_ReportsBytesWritten(int offset, int count)
{
// Arrange
Mock<Stream> mockInnerStream = new Mock<Stream>();
object userState = new object();
IAsyncResult mockIAsyncResult = CreateMockCompletedAsyncResult(true, userState);
mockInnerStream.Setup(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()))
.Returns(mockIAsyncResult);
MockProgressEventHandler mockProgressHandler;
ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressHandler, sendProgress: true);
HttpRequestMessage request = new HttpRequestMessage();
ProgressStream progressStream = ProgressStreamTest.CreateProgressStream(progressMessageHandler: progressMessageHandler, request: request);
// Act
IAsyncResult result = new ProgressWriteAsyncResult(
mockInnerStream.Object, progressStream, sampleData, offset, count, null, userState);
// Assert
Assert.True(mockProgressHandler.WasInvoked);
Assert.Same(request, mockProgressHandler.Sender);
Assert.Equal(count, mockProgressHandler.EventArgs.BytesTransferred);
Assert.Same(userState, mockProgressHandler.EventArgs.UserState);
}
示例7: Execute
public async void Execute(string token, string content)
{
Uri uri = new Uri(API_ADDRESS + path);
var rootFilter = new HttpBaseProtocolFilter();
rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
HttpClient client = new HttpClient(rootFilter);
//client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString());
if(token != null)
client.DefaultRequestHeaders.Add("x-access-token", token);
System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);
HttpResponseMessage response = null;
if (requestType == GET)
{
try
{
response = await client.GetAsync(uri).AsTask(source.Token);
}
catch (TaskCanceledException)
{
response = null;
}
}else if (requestType == POST)
{
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri);
if (content != null)
{
msg.Content = new HttpStringContent(content);
msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
}
try
{
response = await client.SendRequestAsync(msg).AsTask(source.Token);
}
catch (TaskCanceledException)
{
response = null;
}
}
if (response == null)
{
if (listener != null)
listener.onTaskCompleted(null, requestCode);
}
else
{
string answer = await response.Content.ReadAsStringAsync();
if(listener != null)
listener.onTaskCompleted(answer, requestCode);
}
}
示例8: SendRemoteCommandAsync
public async Task<bool> SendRemoteCommandAsync(string pressedKey)
{
bool succeeded = false;
string address = String.Empty;
if (!string.IsNullOrWhiteSpace(pressedKey) && !string.IsNullOrWhiteSpace(_ipAddress))
{
address = "http://" + _ipAddress + "/RemoteControl/KeyHandling/sendKey?key=" + pressedKey;
var uri = new Uri(address, UriKind.Absolute);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri(address);
IHttpContent httpContent = new HttpStringContent(String.Empty);
try
{
await client.PostAsync(uri, httpContent);
}
catch (Exception)
{
return succeeded = false;
}
return succeeded = true;
}
}
return succeeded = false;
}
示例9: Search
public async void Search(object parameter)
{
SongLabelVisibility = "Collapsed";
ArtistLabelVisibility = "Collapsed";
AlbumLabelVisibility = "Collapsed";
if (SearchQuery == "" || SearchQuery == null)
{
return;
}
HttpRequestMessage message = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://mclients.googleapis.com/sj/v1.11/query?q=" + SearchQuery + "&max-results=50", UriKind.Absolute)
};
HttpResponseMessage returnString = await HttpCall.MakeGetCallAsync(message);
var songString = await returnString.Content.ReadAsStringAsync();
AllHits = JsonParser.Parse(songString);
if (AllHits.entries != null)
{
SongHits = Hits.GetSongHits(AllHits.entries, 5);
ArtistHits = Hits.GetArtistHits(AllHits.entries, 5);
AlbumHits = Hits.GetAlbumHits(AllHits.entries, 5);
}
if (SongHits != null && SongHits.Count != 0) { SongLabelVisibility = "Visible"; }
if (ArtistHits != null &&ArtistHits.Count != 0) { ArtistLabelVisibility = "Visible"; }
if (AlbumHits != null &&AlbumHits.Count != 0) { AlbumLabelVisibility = "Visible"; }
OnPropertyChanged("SongHits");
OnPropertyChanged("ArtistHits");
OnPropertyChanged("AlbumHits");
OnPropertyChanged("SongLabelVisibility");
OnPropertyChanged("ArtistLabelVisibility");
OnPropertyChanged("AlbumLabelVisibility");
}
示例10: SendAsync_InsertsReceiveProgressWhenResponseEntityPresent
public Task SendAsync_InsertsReceiveProgressWhenResponseEntityPresent(bool insertResponseEntity, bool addReceiveProgressHandler)
{
// Arrange
HttpMessageInvoker invoker = CreateMessageInvoker(includeResponseEntity: insertResponseEntity, addSendProgressHandler: false, addReceiveProgressHandler: addReceiveProgressHandler);
HttpRequestMessage request = new HttpRequestMessage();
// Act
return invoker.SendAsync(request, CancellationToken.None).ContinueWith(
task =>
{
HttpResponseMessage response = task.Result;
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
// Assert
if (insertResponseEntity && addReceiveProgressHandler)
{
ValidateContentHeader(response.Content);
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
Assert.NotNull(response.Content);
Assert.IsType<StreamContent>(response.Content);
}
else
{
if (insertResponseEntity)
{
Assert.IsType<StringContent>(response.Content);
}
else
{
Assert.Null(response.Content);
}
}
});
}
示例11: SendNotificationAsync
// Post notification
private static async Task SendNotificationAsync(string notificationXML)
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri("https://login.live.com/accesstoken.srf"));
request.Content = new HttpStringContent(string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", Constants.StoreClienId, Constants.StoreClientSecret), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var res = await client.SendRequestAsync(request);
if (res.IsSuccessStatusCode)
{
var tokenJson = await res.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<Token>(tokenJson);
request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(Constants.OwnerNotificationChannel));
request.Content = new HttpStringContent(notificationXML, Windows.Storage.Streams.UnicodeEncoding.Utf8, "text/xml");
(request.Content as HttpStringContent).Headers.ContentLength = Convert.ToUInt64(notificationXML.Length);
request.Headers.Authorization = new HttpCredentialsHeaderValue(token.TokenType, token.AccessToken);
request.Headers.Add("X-WNS-Type", "wns/toast");
await client.SendRequestAsync(request);
}
}
catch (Exception ex)
{
}
}
}
示例12: HttpPost
public static async void HttpPost(string phone, string password)
{
try
{
HttpClient httpClient = new HttpClient();
string posturi = Config.apiUserRegister;
string date = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("phone", phone),//手机号
new KeyValuePair<string, string>("password", password),//密码
new KeyValuePair<string, string>("date", date),//注册日期
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
JsonObject register = JsonObject.Parse(responseString);
try
{
int code = (int)register.GetNamedNumber("code");
switch (code)
{
case 0:
{
JsonObject user = register.GetNamedObject("user");
Config.UserPhone = user.GetNamedString("phone");
NavigationHelp.NavigateTo(typeof(UserData));
break;
}
case 1:
HelpMethods.Msg("手机号已注册!");
break;
case 2:
HelpMethods.Msg("未知错误!");
break;
default:
break;
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例13: HttpPost
public static async void HttpPost(string phone, string password)
{
try
{
HttpClient httpClient = new HttpClient();
string posturi = Config.apiUserLogin;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("phone", phone),//手机
new KeyValuePair<string, string>("password", password),//密码
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
JsonObject login = JsonObject.Parse(responseString);
try
{
int code = (int)login.GetNamedNumber("code");
switch (code)
{
case 0:
{
JsonObject user = login.GetNamedObject("user");
Config.UserName = user.GetNamedString("name") ;
Config.UserImage = Config.apiFile + user.GetNamedString("image");
Config.UserPhone = user.GetNamedString("phone") ;
Config.UserDream = user.GetNamedString("dream") ;
Config.UserTag = user.GetNamedString("tag");
NavigationHelp.NavigateTo(typeof(Main));
break;
}
case 1:
HelpMethods.Msg("手机号未注册!");
break;
case 2:
HelpMethods.Msg("密码错误!");
break;
default:
break;
}
}
catch (Exception ex)
{
HelpMethods.Msg("服务器出错!");
Debug.WriteLine(ex.Message.ToString());
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例14: generateUploadRequest
private static HttpRequestMessage generateUploadRequest(string address,
string fileName, string fileContents, string mimeType,
Dictionary<string, string> parameters)
{
var rnd = new Random();
long boundarySeed = (long)(rnd.NextDouble() * 1000000000);
string boundary = boundarySeed.ToString();
string contentType = "multipart/form-data; boundary=" + boundary;
string partBoundary = "--" + boundary;
string requestBody = "\r\n" + partBoundary + "\r\n";
requestBody += "Content-Disposition: form-data; name=\"" + POSTKeys.POST_UPLOADED_FILE + "\"; filename=\"" + fileName + "\"\r\n";
requestBody += "Content-Type: " + mimeType + "\r\n\r\n";
requestBody += fileContents + "\r\n";
foreach (var parameter in parameters)
{
requestBody += partBoundary + "\r\n";
requestBody += "Content-Disposition: form-data; name=\"" + parameter.Key + "\"\r\n\r\n";
requestBody += parameter.Value + "\r\n";
}
requestBody += "--" + boundary + "--";
HttpRequestMessage uploadRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(address));
uploadRequest.Content = new HttpStringContent(requestBody);
uploadRequest.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType);
uploadRequest.Content.Headers.ContentLength = (ulong?)requestBody.Length;
return uploadRequest;
}
示例15: GetBearerTokenAsync
async Task GetBearerTokenAsync()
{
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2Token));
req.Headers.Add("Authorization", "Basic " + BasicToken);
req.Headers.Add("User-Agent", UserAgent);
req.Headers.Add("Expect", "100-continue");
req.Content = new HttpStringContent("grant_type=client_credentials", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var baseFilter = new HttpBaseProtocolFilter
{
AutomaticDecompression = SupportsCompression,
ProxyCredential = ProxyCredential,
UseProxy = UseProxy
};
using (var client = new HttpClient(baseFilter))
{
var msg = await client.SendRequestAsync(req);
await TwitterErrorHandler.ThrowIfErrorAsync(msg);
string response = await msg.Content.ReadAsStringAsync();
var responseJson = JsonMapper.ToObject(response);
BearerToken = responseJson.GetValue<string>("access_token");
}
}