本文整理汇总了C#中System.Net.Http.HttpClient.Send方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.Send方法的具体用法?C# HttpClient.Send怎么用?C# HttpClient.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClient
的用法示例。
在下文中一共展示了HttpClient.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Create_New_Customer
public void Create_New_Customer()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
client.Channel = new WebRequestChannel();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers");
request.Content = new StringContent("Id = 7; Name = NewCustomer7");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'.");
Assert.IsNotNull(response.Headers.Location, "The location header should not have been null.");
Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'.");
Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'.");
}
// Put server back in original state
request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7");
client.Send(request);
}
}
示例2: RunClient
public static ICollection<HttpResponseMessage> RunClient(HttpClient client, TestHeaderOptions options, HttpMethod method)
{
var result = new HttpResponseMessage[TestServiceCommon.Iterations];
for (var cnt = 0; cnt < TestServiceCommon.Iterations; cnt++)
{
var httpRequest = new HttpRequestMessage(method, "");
if ((options & TestHeaderOptions.InsertRequest) > 0)
{
TestServiceCommon.AddRequestHeader(httpRequest, cnt);
}
try
{
result[cnt] = client.Send(httpRequest);
Assert.IsNotNull(result[cnt]);
}
catch (HttpException he)
{
var we = he.InnerException as WebException;
Assert.IsNull(we.Response, "Response should not be null.");
continue;
}
if ((options & TestHeaderOptions.ValidateResponse) > 0)
{
TestServiceCommon.ValidateResponseTestHeader(result[cnt], cnt);
}
}
Assert.AreEqual(TestServiceCommon.Iterations, result.Length);
return result;
}
示例3: Main
private static void Main(string[] args)
{
// create the event loop
var loop = new EventLoop();
// start it with a callback
loop.Start(() => Console.WriteLine("Event loop has started"));
// start a timer
loop.SetTimeout(() => Console.WriteLine("Hello, I am a timeout happening after 1 second"), TimeSpan.FromSeconds(1));
loop.SetInterval(() => Console.WriteLine("Hello, I am an interval happening every 2 seconds"), TimeSpan.FromSeconds(2));
// read the app.config
var appConfigFile = new FileInfo("NLoop.TestApp.exe.config");
var promise = appConfigFile.ReadAllBytes(loop);
promise.Then(content => Console.WriteLine("Success!! read {0} bytes from app.config", content.Length), reason => Console.WriteLine("Dread!! got an error: {0}", reason));
// send a web request
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/");
var httpPromise = httpClient.Send(loop, request);
httpPromise.Then(content => Console.WriteLine("Success!! read {0} from google.com", content.StatusCode), reason => Console.WriteLine("Dread!! got an error: {0}", reason));
//httpPromise.Cancel();
// wait
Console.WriteLine("Event loop is processing, press any key to exit");
Console.Read();
// we are done, dispose the loop so resources will be cleaned up
loop.Dispose();
}
示例4: NextState
public IApplicationState NextState(HttpClient client)
{
if (applicationStateInfo.Endurance < 1)
{
return new Defeated(currentResponse, applicationStateInfo);
}
if (currentResponse.Content.Headers.ContentType.Equals(AtomMediaType.Feed))
{
var feed = currentResponse.Content.ReadAsObject<SyndicationFeed>(AtomMediaType.Formatter);
if (feed.Categories.Contains(new SyndicationCategory("encounter"), CategoryComparer.Instance))
{
var form = Form.ParseFromFeedExtension(feed);
form.Fields.Named("endurance").Value = applicationStateInfo.Endurance.ToString();
var newResponse = client.Send(form.CreateRequest(feed.BaseUri));
if (newResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
{
var newContent = newResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);
var newForm = Form.ParseFromEntryContent(newContent);
var newEndurance = int.Parse(newForm.Fields.Named("endurance").Value);
return new ResolvingEncounter(newResponse, applicationStateInfo.GetBuilder().UpdateEndurance(newEndurance).Build());
}
}
return new Error(currentResponse, applicationStateInfo);
}
if (currentResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
{
var entry = currentResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);
if (entry.Categories.Contains(new SyndicationCategory("room"), CategoryComparer.Instance))
{
return new Exploring(currentResponse, applicationStateInfo);
}
var continueLink = entry.Links.FirstOrDefault(l => l.RelationshipType.Equals("continue"));
if (continueLink != null)
{
return new ResolvingEncounter(client.Get(new Uri(entry.BaseUri, continueLink.Uri)), applicationStateInfo);
}
var form = Form.ParseFromEntryContent(entry);
var newResponse = client.Send(form.CreateRequest(entry.BaseUri));
if (newResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
{
var newContent = newResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);
var newForm = Form.ParseFromEntryContent(newContent);
var newEndurance = int.Parse(newForm.Fields.Named("endurance").Value);
return new ResolvingEncounter(newResponse, applicationStateInfo.GetBuilder().UpdateEndurance(newEndurance).Build());
}
}
return new Error(currentResponse, applicationStateInfo);
}
示例5: twitterSample
private static void twitterSample()
{
var client = new HttpClient(Urls.Twitter)
{
Channel = new HttpMessageInspector(new WebRequestChannel())
};
var request = new HttpRequestMessage(HttpMethod.Get, "1/users/show/{0}.xml".FormatWith("duarte_nunes"));
request.With().Accept("application/xml");
HttpResponseMessage response = client.Send(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(response.Content.ReadAsString());
XElement element = response.Content.ReadAsXElement();
Console.WriteLine(element.Element("description").Value);
var formatter = new JsonDataContractFormatter(new DataContractJsonSerializer(typeof(TwitterUser)));
var c = new RestyClient<TwitterUser>(Urls.Twitter, new[] { formatter });
Tuple<HttpStatusCode, TwitterUser> result = c.ExecuteGet("1/users/show/{0}.json".FormatWith("duarte_nunes"));
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2.Description);
Console.WriteLine(result.Item2.ProfileImageUrl);
}
示例6: GetResponse
private static HttpResponseMessage GetResponse(ServiceHost host, HttpRequestMessage request)
{
UriBuilder builder = new UriBuilder(host.BaseAddresses[0]);
builder.Host = Environment.MachineName;
request.RequestUri = new Uri(request.RequestUri.ToString(), UriKind.Relative);
using (HttpClient client = new HttpClient(builder.Uri))
{
client.Channel = new WebRequestChannel();
return client.Send(request);
}
}
示例7: Create_Customer_That_Already_Exists
public void Create_Customer_That_Already_Exists()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers?id=2");
request.Content = new StringContent("Id = 2; Name = AlreadyCustomer2");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.Conflict, response.StatusCode, "The status code should have been 'Conflict'.");
Assert.AreEqual("There already a customer with id '2'.", response.Content.ReadAsString(), "The response content should have been 'There already a customer with id '2'.'");
}
}
}
示例8: RetrievePageHtml
public string RetrievePageHtml(int pageNumber)
{
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.UseCookies = false;
using (HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://www.rllmukforum.com/");
var url = string.Format("{0}/page-{1}", ConfigurationManager.AppSettings["ThreadBaseAddress"], pageNumber);
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, url);
var requestUri = message.RequestUri;
foreach (var cookieHeader in _signedInHeaders.Where(h => string.Equals(h.Key, "Set-Cookie")))
{
message.Headers.Add("Cookie", cookieHeader.Value);
}
var response = client.Send(message);
var currentUri = response.RequestMessage.RequestUri.AbsoluteUri;
var index = currentUri.IndexOf("page", StringComparison.OrdinalIgnoreCase);
var currentActualPageNumber = index == -1 ? 1 : int.Parse(currentUri.Substring(index + 5, currentUri.Length - (index + 5)));
if (pageNumber != currentActualPageNumber)
{
return string.Empty;
}
return response.GetContentAsString();
}
}
}
示例9: Delete_Existing_Customer
public void Delete_Existing_Customer()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=3");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The status code should have been 'OK'.");
Assert.AreEqual(string.Empty, response.Content.ReadAsString(), "The response content should have been an empty string.");
}
// Put server back in the original state
request = new HttpRequestMessage(HttpMethod.Post, "Customers");
request.Content = new StringContent("Id = 3; Name = Customer3");
client.Send(request);
}
}
示例10: Send_SameMessage
public void Send_SameMessage ()
{
var mh = new HttpMessageHandlerMock ();
var client = new HttpClient (mh);
var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
mh.OnSend = l => {
return new HttpResponseMessage ();
};
client.Send (request);
try {
client.Send (request);
} catch (InvalidOperationException) {
}
}
示例11: Send_InvalidHandler
public void Send_InvalidHandler ()
{
var mh = new HttpMessageHandlerMock ();
var client = new HttpClient (mh);
client.BaseAddress = new Uri ("http://xamarin.com");
var request = new HttpRequestMessage ();
mh.OnSend = l => {
Assert.AreEqual (l, request, "#1");
return null;
};
try {
client.Send (request);
Assert.Fail ("#2");
} catch (InvalidOperationException) {
}
}
示例12: Send_Invalid
public void Send_Invalid ()
{
var client = new HttpClient ();
try {
client.Send (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
var request = new HttpRequestMessage ();
client.Send (request);
Assert.Fail ("#2");
} catch (InvalidOperationException) {
}
}
示例13: Send_Complete_Error
public void Send_Complete_Error ()
{
var listener = CreateListener (l => {
var response = l.Response;
response.StatusCode = 500;
});
try {
var client = new HttpClient ();
var request = new HttpRequestMessage (HttpMethod.Get, LocalServer);
var response = client.Send (request, HttpCompletionOption.ResponseHeadersRead);
Assert.AreEqual ("", response.Content.ReadAsString (), "#100");
Assert.AreEqual (HttpStatusCode.InternalServerError, response.StatusCode, "#101");
} finally {
listener.Close ();
}
}
示例14: Update_Non_Existing_Customer
public void Update_Non_Existing_Customer()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
client.Channel = new WebRequestChannel();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "Customers?id=5");
request.Content = new StringContent("Id = 5; Name = NewCustomerName1");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode, "The status code should have been 'NotFound'.");
Assert.AreEqual("There is no customer with id '5'.", response.Content.ReadAsString(), "The response content should have been 'There is no customer with id '5'.'");
}
}
}
示例15: Get_With_Non_Integer_Id
public void Get_With_Non_Integer_Id()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
client.Channel = new WebRequestChannel();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "Customers?id=foo");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode, "The status code should have been 'BadRequest'.");
Assert.AreEqual("An 'id' with a integer value must be provided in the query string.", response.Content.ReadAsString(), "The response content should have been 'An 'id' with a integer value must be provided in the query string.'");
}
}
}