本文整理汇总了C#中Microsoft.Http.HttpClient.Send方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.Send方法的具体用法?C# HttpClient.Send怎么用?C# HttpClient.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Http.HttpClient
的用法示例。
在下文中一共展示了HttpClient.Send方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ListAllContacts
static void ListAllContacts()
{
using (HttpClient client = new HttpClient("http://localhost:9000/api/contacts/"))
{
//Get
Console.WriteLine("Get-Method Test...");
using (var request = new HttpRequestMessage("GET", "Get/1/name"))
{
request.Headers.Accept.Add("application/json");
using (var response = client.Send(request))
{
var status = response.StatusCode;
Console.WriteLine("Status Code: {0}", status);
var result = response.Content.ReadAsString();
Console.WriteLine("Content: {0}", result);
}
}
//Post
Console.WriteLine("Post-Method Test...");
HttpContent content = HttpContentExtensions
.CreateJsonDataContract(new List<Contact>
{
new Contact{Name = "王春雷"},
new Contact{ContactId = 1,Name = "老张"}
});
content.LoadIntoBuffer();
using (var response = client.Put("Filter/1/王春雷", content))
{
response.EnsureStatusIsSuccessful();
response.Content.LoadIntoBuffer();
var result = response.Content.ReadAsJsonDataContract<List<Contact>>();
//var serializer = new JavaScriptSerializer();
//var con=serializer.Deserialize<List<Contact>>(result);
result.ForEach(r => Console.WriteLine(r.ToString()));
}
}
Console.ReadKey();
}
示例2: GetProductsWithQueryStringRelative
public void GetProductsWithQueryStringRelative()
{
var serializer = new XmlSerializer(typeof(Crawler.Model.LinkShare.result));
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://feed.linksynergy.com");
HttpQueryString query = new HttpQueryString();
query.Add("token", "5bfb339580a02308573204c2ac1bb921ecba09ba542a19d271c2d7e9c27a509f");
query.Add("keyword", "DVD Player");
query.Add("Page", "1");
query.Add("MaxResults", "100");
var uri = HttpQueryString.MakeQueryString(new Uri("/productsearch?", UriKind.Relative), query);
var req = new HttpRequestMessage("GET", uri);
using (var response = client.Send(req))
{
//string results = response.Content.ReadAsString();
var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
}
}
示例3: GetProductsWithQueryStringRelative
public void GetProductsWithQueryStringRelative()
{
var serializer = new XmlSerializer(typeof(Crawler.Model.CJ.cjapi));
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://product-search.api.cj.com");
HttpQueryString query = new HttpQueryString();
query.Add("website-id", "3100204");
query.Add("keywords", "DVD");
query.Add("page-number", "1");
query.Add("records-per-page", "1000");
var uri = HttpQueryString.MakeQueryString(new Uri("/v2/product-search?", UriKind.Relative), query);
var req = new HttpRequestMessage("GET", uri);
req.Headers.Add("authorization", "00b171e48c4bc1e70836b252e1c4c40a893f19db0457be8447b1acdbdc0e7e769e1b804c1af54f883326d6147d1365f4b5f031a61740cf0c63a9f4b3d174cebbbf/420a385c3aa9bcd962b9f57ccf2583225758c11999aa6f42db8e90f9126fe0a7110790cd2ccd66a4f1861e89bd33fcfa6f528b494fa183f5d380ca289d18c309");
using (var response = client.Send(req))
{
//string results = response.Content.ReadAsString();
var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
}
}
示例4: ExecuteServiceMethod
/// <summary>
/// Static method to request a webservice and get the response content
/// </summary>
/// <param name="service">Request Object</param>
/// <returns>Response Object</returns>
public static HttpResponseMessage ExecuteServiceMethod(WebServiceUrl service, string userName, string password)
{
HttpResponseMessage response = null;
isOem = service.IsOem;
try
{
using (var webClient = new HttpClient())
{
webClient.DefaultHeaders.Add("Content-Type", "application/xml;charset=utf-8");
webClient.DefaultHeaders.Add("Authorization", GetAuthHeader(userName, password));
if (service.Method == HttpMethod.POST)
{
response = webClient.Send(service.Method, service.Url,
HttpContent.Create(requestHeader + service.Request, "application/xml"));
}
else
{
if (service.Request != null && service.Request.ToString().Length > 0)
{
service.Url += string.Format("/{0}", service.Request.ToString());
}
response = webClient.Get(service.Url);
}
}
}
catch (Exception e)
{
TextLog.LogMessage("Faile to request the web service with the exception : " + e.Message);
throw ;
}
return response;
}
示例5: ExecuteTask
protected override void ExecuteTask()
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
{
client.DefaultHeaders.Authorization = Credential.CreateBasic(UserName, Password);
}
if (!string.IsNullOrEmpty(Method))
{
request.Method = Method;
}
request.Uri = new Uri(Url);
if (!string.IsNullOrEmpty(ContentType))
{
request.Headers.ContentType = ContentType;
}
if (!request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
{
request.Content = (string.IsNullOrEmpty(Content)) ? HttpContent.CreateEmpty() : HttpContent.Create(Content);
request.Headers.ContentLength = request.Content.GetLength();
}
if (ConnectionTimeout != 0)
{
client.TransportSettings.ConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout);
}
Project.Log(Level.Info, "Executing HTTP request.");
Project.Log(Level.Info, "Url: {0}", request.Uri);
Project.Log(Level.Info, "Method: {0}", request.Method);
Project.Log(Level.Info, "Content Type: {0}", request.Headers.ContentType);
Project.Log(Level.Info, "Connection Timeout: {0}", client.TransportSettings.ConnectionTimeout);
try
{
HttpResponseMessage response = client.Send(request);
if (FailOnError)
{
response.EnsureStatusIsSuccessful();
}
if (!string.IsNullOrEmpty(StatusCodeProperty))
{
Project.Properties[StatusCodeProperty] = response.StatusCode.ToString();
}
if (successCodes.Contains(response.StatusCode) && !string.IsNullOrEmpty(ResponseProperty))
{
Project.Properties[ResponseProperty] = response.Content.ReadAsString();
}
Project.Log(Level.Info, "Received HTTP response.");
Project.Log(Level.Info, "Status Code: {0}", response.StatusCode);
Project.Log(Level.Info, "Content Type: {0}", response.Headers.ContentType);
}
catch (ArgumentOutOfRangeException ex)
{
string message = string.Format("The HTTP '{0}' request to '{1}' failed:{2}{3}", Method, Url, Environment.NewLine, ex.Message);
throw new BuildException(message, ex);
}
}
示例6: SearchResults_SelectedIndexChanged
/// <summary>
/// Example of calling Actor.svc/participant to get participant details
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void SearchResults_SelectedIndexChanged(object sender, EventArgs e)
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
string clid = null;
using (HttpClient client = new HttpClient(baseurl))
{
RequestHeaders headers = new RequestHeaders();
headers.Add("enterpriseGuid", enterprise);
headers.Add("securityToken", Session["SecurityToken"].ToString());
clid = SearchResults.SelectedValue;
HttpResponseMessage resp = client.Send(HttpMethod.GET, "Actor.svc/participant/" + clid, headers);
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Participant));
Participant participant = (Participant)ser.ReadObject(resp.Content.ReadAsStream());
PartNameLabel.Text = participant.FirstName + " " + participant.LastName;
PartIdLabel.Text = participant.ID.ToString();
PartAddrLabel.Text = participant.Address1 + " " + participant.Address2;
PartGenderLabel.Text = participant.Gender.ToString();
}
DisplayAssessments(clid);
}
示例7: LogonSite
/// <summary>
/// Example of calling Security.svc/getsiteinfo to log into
/// a specific site.
/// </summary>
private void LogonSite()
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string authtoken = Session["AuthToken"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
using (HttpClient client = new HttpClient(baseurl))
{
HttpResponseMessage resp = client.Send(HttpMethod.GET, string.Format("Security.svc/SSOSiteLogin/{0}/{1}/{2}/-300", siteid, enterprise, authtoken));
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer siteSer = new DataContractJsonSerializer(typeof(string));
string SiteLoginResponse = siteSer.ReadObject(resp.Content.ReadAsStream()) as string;
Session["SecurityToken"] = SiteLoginResponse;
}
}
示例8: DisplaySiteInfo
/// <summary>
/// Example of calling Security.svc/getsiteinfo to display details
/// for a specific site.
/// </summary>
private void DisplaySiteInfo()
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
string securitytoken = Session["SecurityToken"].ToString();
string authtoken = Session["AuthToken"].ToString();
using (HttpClient client = new HttpClient(baseurl))
{
RequestHeaders headers = new RequestHeaders();
headers.Add("Content-Type", "application/json");
headers.Add("enterpriseGuid", enterprise);
headers.Add("securityToken", securitytoken);
HttpResponseMessage resp = client.Send(HttpMethod.GET, "Security.svc/GetSiteInfo/" + siteid, headers);
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer siteSer = new DataContractJsonSerializer(typeof(SiteInfo));
SiteInfo siteInfo = (SiteInfo)siteSer.ReadObject(resp.Content.ReadAsStream());
SiteNameLabel.Text = siteInfo.SiteName;
AddressLabel.Text = siteInfo.Address1 + " " + siteInfo.Address2;
PhoneLabel.Text = siteInfo.PhoneNumber;
ZipLabel.Text = siteInfo.ZipCode;
DisabledLabel.Text = siteInfo.Disabled ? "Yes" : "No";
}
}
示例9: DisplayPrograms
/// <summary>
/// Example of calling Form.svc/Forms/Program/GetPrograms to get a
/// list of programs for a specific site.
/// </summary>
private void DisplayPrograms()
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
using (HttpClient client = new HttpClient(baseurl))
{
RequestHeaders headers = new RequestHeaders();
headers.Add("enterpriseGuid", enterprise);
headers.Add("securityToken", Session["SecurityToken"].ToString());
HttpResponseMessage resp = client.Send(HttpMethod.GET, "Form.svc/Forms/Program/GetPrograms/" + siteid, headers);
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ProgramInfo[]));
ProgramInfo[] progInfo = (ProgramInfo[])ser.ReadObject(resp.Content.ReadAsStream());
foreach (ProgramInfo pinfo in progInfo)
{
ProgramDropList.Items.Add(new ListItem(pinfo.Name, pinfo.ID.ToString()));
}
}
}
示例10: DisplayAssessments
/// <summary>
/// Example of calling Form.svc/Forms/Assessments/GetAllAssessementResponses
/// to get a list of assessment responses for a participant.
/// </summary>
/// <param name="clid"></param>
private void DisplayAssessments(string clid)
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
using (HttpClient client = new HttpClient(baseurl))
{
RequestHeaders headers = new RequestHeaders();
headers.Add("enterpriseGuid", enterprise);
headers.Add("securityToken", Session["SecurityToken"].ToString());
string body = "{\"CLID\":\"";
body = body + clid + "\",\"surveyResponderType\":";
body = body + (int)SurveyResponderType.Client + "}";
HttpResponseMessage resp = client.Send(HttpMethod.POST,
"Form.svc/Forms/Assessments/GetAllAssessementResponses/",
headers, HttpContent.Create(body, "application/json; charset=utf-8"));
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AssessmentResponse[]));
AssessmentResponse[] responses = (AssessmentResponse[])ser.ReadObject(resp.Content.ReadAsStream());
foreach (AssessmentResponse response in responses)
{
Panel2.Controls.Add(new LinkButton() { Text = response.SurveyName + " " + response.SurveyDate.ToString() + " " +
response.SurveyResponseID.ToString() + " " + response.SurveyTaker });
}
}
}
示例11: SearchText_TextChanged
/// <summary>
/// Example of calling Search.svc/Search/ to search for participants
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void SearchText_TextChanged(object sender, EventArgs e)
{
string siteid = Session["SessionID"].ToString();
string enterprise = Session["EnterpriseGUID"].ToString();
string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
using (HttpClient client = new HttpClient(baseurl))
{
RequestHeaders headers = new RequestHeaders();
headers.Add("enterpriseGuid", enterprise);
headers.Add("securityToken", Session["SecurityToken"].ToString());
string programId = ProgramDropList.SelectedValue;
string searchtext = SearchText.Text;
HttpResponseMessage resp = client.Send(HttpMethod.GET, "Search.svc/Search/" + programId + "/" + searchtext, headers);
resp.EnsureStatusIsSuccessful();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SearchResult[]));
SearchResult[] results = (SearchResult[])ser.ReadObject(resp.Content.ReadAsStream());
if (results.Length == 0)
{
SearchResults.Items.Clear();
}
else
{
foreach (SearchResult result in results)
{
SearchResults.Items.Add(new ListItem(result.FName + " " + result.LName, result.CLID.ToString()));
}
}
}
}