最近的工作需要使用Bot Framework调用原有的WebAPI查询数据,查找了一些方法,大部分都是使用HttpClient调用的,现时贴出代码供参考
using System;using System.Collections.Generic;using System.Linq;using System.Net.Http;using System.Threading.Tasks;using System.Web;using System.Text;using Newtonsoft.Json;using System.Net;namespace esquel_LPD_Bot.LPDService{ public class GarmentStyleHelper { public async TaskGarmentStyleSearch(string pi_GarmentStyleNo) { string l_returnValue = string.Empty; string l_APIUrl = Common.ConfigHelper.GetConfigValue("LPD-GarmentStyleSearchAPIUrl"); Common.LPDAuthHelper LPDAuthClass = new Common.LPDAuthHelper(); try { if(string.IsNullOrEmpty( LPDAuthClass.UserName)|| string.IsNullOrEmpty(LPDAuthClass.UserName)) { throw new Exception("LPD Project Auth User Name Or Password Is Empty ."); } if (!string.IsNullOrEmpty(l_APIUrl) && !string.IsNullOrEmpty(pi_GarmentStyleNo)) { var request = new Model.SelectionFilter() { FilterType = Model.SelectionFilter.FilterTypeLeaf, Filters = new Model.SelectionFilter[] { }, AttributeName = "item_number", FilterValue = pi_GarmentStyleNo }; //-------------------------------------------------------------------------------------------- var handler = new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip }; //handler.UseDefaultCredentials = true;//use default network利用的用户本机的网络,但因为需要布署到服务器,所以使用以下这一句 handler.Credentials=new NetworkCredential(LPDAuthClass.UserName, LPDAuthClass.PassWord);//设定权限,这一句比较痛苦,找了很久 using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsync(l_APIUrl, new StringContent(JsonConvert.SerializeObject(request).ToString(), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); string l_getreturn = await response.Content.ReadAsStringAsync(); l_returnValue = l_getreturn; } } } catch (Exception ex) { } return l_returnValue; } }}
参考地址:
http://www.cnblogs.com/validvoid/p/demystifying-httpclient-apis-in-the-uwp.html 使用身份验证凭据
http://www.cnblogs.com/lori/p/4045633.html