本文整理汇总了C#中HttpClient.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.Dispose方法的具体用法?C# HttpClient.Dispose怎么用?C# HttpClient.Dispose使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpClient
的用法示例。
在下文中一共展示了HttpClient.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendGetRequest
static public async Task<string> SendGetRequest ( string address )
{
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";
}
//get
try
{
response = await httpClient.GetAsync ( resourceUri );
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;
}
示例2: GetVideoStream
public async static Task<UriShieldData> GetVideoStream(string url)
{
var client = new HttpClient();
string message;
try
{
if (url.EndsWith("Manifest"))
{
url += "?type=json&protection=url";
}
else
{
url += "&type=json&protection=url";
}
var response = await client.GetStringAsync(new Uri(url));
UriShieldData data = new UriShieldData();
data.Subtitles = false;
data.Url = JsonConvert.DeserializeObject<string>(response);
client.Dispose();
return data;
}
catch (Exception hrex)
{
message = hrex.Message;
client.Dispose();
}
MessageBox.Show(string.Format(ResourceHelper.GetString("WebErrorMessage"), message));
return new UriShieldData();
}
示例3: SendRequest
public async Task<bool> SendRequest()
{
try
{
var config = new ConfigurationViewModel();
var uri = new Uri(config.Uri + _path);
var filter = new HttpBaseProtocolFilter();
if (config.IsSelfSigned == true)
{
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
}
var httpClient = new HttpClient(filter);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain"));
httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString()));
httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString()));
var reponse = await httpClient.GetAsync(uri);
httpClient.Dispose();
return reponse.IsSuccessStatusCode;
}
catch (Exception)
{
return false;
}
}
示例4: GetPlaylistAsync
public static async Task<Album> GetPlaylistAsync(string link)
{
try
{
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 45.0.2454.101 Safari / 537.36"));
string htmlPage = await hc.GetStringAsync(new Uri(link));
string xmlLink = Regex.Split(htmlPage, "amp;file=")[1].Split('\"')[0];
XDocument xdoc = XDocument.Parse(await hc.GetStringAsync(new Uri(xmlLink)));
hc.Dispose();
//Parse xml
var trackList = from t in xdoc.Descendants("track")
select new Track()
{
Title = t.Element("title").Value,
Artist = t.Element("creator").Value,
Location = t.Element("location").Value,
Info = t.Element("info").Value,
ArtistLink = t.Element("newtab").Value,
Image = t.Element("bgimage").Value
};
Album album = new Album();
album.Link = link;
album.TrackList = trackList.ToList();
return album;
}
catch (Exception)
{
return null;
}
}
示例5: DoLogin
/// <summary>
/// 约定成功登陆返回0,不成功返回错误代码,未知返回-1
/// </summary>
/// <returns></returns>
public async Task<int> DoLogin()
{
var httpClient = new HttpClient();
var requestUrl = "https://net.zju.edu.cn/cgi-bin/srun_portal";
var formcontent = new HttpFormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("action","login"),
new KeyValuePair<string, string>("username",_mAccount.Username),
new KeyValuePair<string, string>("password",_mAccount.Password),
new KeyValuePair<string, string>("ac_id","3"),
new KeyValuePair<string, string>("type","1"),
new KeyValuePair<string, string>("wbaredirect",@"http://www.qsc.zju.edu.cn/"),
new KeyValuePair<string, string>("mac","undefined"),
new KeyValuePair<string, string>("user_ip",""),
new KeyValuePair<string, string>("is_ldap","1"),
new KeyValuePair<string, string>("local_auth","1"),
});
var response = await httpClient.PostAsync(new Uri(requestUrl), formcontent);
if (response.Content != null)
{
string textMessage = await response.Content.ReadAsStringAsync();
Debug.WriteLine(textMessage);
}
httpClient.Dispose();
return -1;
}
示例6: Authenticate
public static async Task<string> Authenticate()
{
var startURI = new Uri(START_URL);
var endURI = new Uri(END_URL);
string result;
var webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);
switch (webAuthResult.ResponseStatus)
{
case WebAuthenticationStatus.Success:
result = webAuthResult.ResponseData.ToString();
break;
case WebAuthenticationStatus.ErrorHttp:
result = webAuthResult.ResponseData.ToString();
throw new Exception(result);
default:
throw new Exception("Error :(");
}
var resultURI = new Uri(result);
var query = resultURI.ParseQueryString();
var code = query["code"];
var tokenURL = "https://api.slack.com/api/oauth.access?code="
+ Uri.EscapeUriString(code)
+ "&client_id=" + Uri.EscapeUriString(CLIENT_ID)
+ "&client_secret=" + Uri.EscapeUriString(CLIENT_SECRET);
var tokenURI = new Uri(tokenURL);
var httpClient = new HttpClient();
string tokenResponse;
try
{
tokenResponse = await httpClient.GetStringAsync(tokenURI);
}
catch (Exception)
{
throw;
}
finally
{
httpClient.Dispose();
}
JsonObject tokenObject;
if (!JsonObject.TryParse(tokenResponse, out tokenObject))
{
throw new Exception("Couldn't parse HTTP response. Try again later.");
}
if (!tokenObject.GetNamedBoolean("ok"))
{
throw new Exception("You are not authorized to access this team.");
}
return tokenObject.GetNamedString("access_token");
}
示例7: CreateHttpClient
internal static void CreateHttpClient(ref HttpClient httpClient)
{
if (httpClient != null)
{
httpClient.Dispose();
}
//添加过滤器
IHttpFilter filter = new HttpBaseProtocolFilter();
filter = new PlugInFilter(filter);
httpClient = new HttpClient(filter);
//添加User-Agent
httpClient.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("mySample", "v1"));
}
示例8: PostWebServiceDataAsync
private async Task PostWebServiceDataAsync(string mediaId)
{
try
{
Random random = new Random();
int r = random.Next();
string requestUrl = "http://replatform.cloudapp.net:8000/userAction?uuid={0}&type={1}&media_id={2}&from={3}&to={4}&r={5}";
string userid = App.gDeviceName;
requestUrl = String.Format(requestUrl, userid, App.gDeviceType, mediaId, App.NavigationRoadmap.GetFrom(), App.NavigationRoadmap.GetTo(), r);
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.AutomaticDecompression = true;
HttpClient httpClient = new HttpClient(filter);
CancellationTokenSource cts = new CancellationTokenSource();
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;
Uri resourceUri;
if (!Uri.TryCreate(requestUrl.Trim(), UriKind.Absolute, out resourceUri))
{
return;
}
HttpResponseMessage response = await httpClient.GetAsync(resourceUri).AsTask(cts.Token);
string jsonText = await Helpers.GetResultAsync(response, cts.Token);
GetPostUserActionResult(jsonText);
if (filter != null)
{
filter.Dispose();
filter = null;
}
if (httpClient != null)
{
httpClient.Dispose();
httpClient = null;
}
if (cts != null)
{
cts.Dispose();
cts = null;
}
}
catch (Exception) { }
}
示例9: GetTaiwanUVData
//透過HttpClient 去取得紫外線Open Data
public async Task<List<TaiwanCityUV>> GetTaiwanUVData()
{
List<TaiwanCityUV> taiwanUVData = new List<TaiwanCityUV>();
string content = "";
HttpClient httpClient = new HttpClient();
try
{
content = await httpClient.GetStringAsync(new Uri(TaiwanUVOpenDataUrl));
RawContent = content;
JsonArray jArray = JsonArray.Parse(content);
IJsonValue outValue;
string testContent = "";
foreach (var item in jArray)
{
JsonObject obj = item.GetObject();
// Assume there is a “backgroundImage” column coming back
if (obj.TryGetValue("SiteName", out outValue))
{
testContent += outValue.GetString() + " ";
}
}
RawContent = testContent;
RawContent = "There are " + taiwanUVData.Count + " " + RawContent;
taiwanUVData=DeserializeTaiwanUVJason(content);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message+ " "+ ex.StackTrace);
var telemetry = new TelemetryClient();
telemetry.TrackException(ex);
}
// Once your app is done using the HttpClient object call dispose to
httpClient.Dispose();
return taiwanUVData;
}
示例10: CreateHttpClient
internal static void CreateHttpClient(ref HttpClient httpClient)
{
if (httpClient != null)
{
httpClient.Dispose();
}
// HttpClient functionality can be extended by plugging multiple filters together and providing
// HttpClient with the configured filter pipeline.
IHttpFilter filter = new HttpBaseProtocolFilter();
filter = new PlugInFilter(filter); // Adds a custom header to every request and response message.
httpClient = new HttpClient(filter);
// The following line sets a "User-Agent" request header as a default header on the HttpClient instance.
// Default headers will be sent with every request sent from this HttpClient instance.
httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("Sample", "v8"));
}
示例11: GetTopTrackListAsync
public static async Task<Album> GetTopTrackListAsync(string link)
{
Album album = new Album();
album.Link = link;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 45.0.2454.101 Safari / 537.36"));
string response = await client.GetStringAsync(new Uri(link));
client.Dispose();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(response);
//Lay album title tu header
album.Title = doc.DocumentNode.ChildNodes["html"].ChildNodes["head"].ChildNodes["title"].InnerText;
//Chon ra the ul chua danh sach bai hat
var ulTags = from ul in doc.DocumentNode.Descendants("ul").Where(x => x.Attributes["class"].Value == "list_show_chart")
select ul;
var ulTag = ulTags.First();
//Moi node la 1 the li
foreach (HtmlNode node in ulTag.ChildNodes)
{
//Loai bo the #text
if (node.Name == "li")
{
try
{
HtmlNode trackInfoNode = node.ChildNodes[5];
Track track = new Track();
track.Title = trackInfoNode.ChildNodes[3].ChildNodes[0].InnerText;
track.Info = trackInfoNode.ChildNodes[3].ChildNodes[0].Attributes["href"].Value;
track.Image = trackInfoNode.ChildNodes[1].ChildNodes["img"].Attributes["src"].Value;
track.Artist = trackInfoNode.ChildNodes[5].ChildNodes[1].InnerText;
track.ArtistLink = trackInfoNode.ChildNodes[5].ChildNodes[1].Attributes["href"].Value;
album.TrackList.Add(track);
}
catch (Exception)
{ }
}
}
return album;
}
示例12: GetJson
public int GetJson(out string jsonFile)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource(3000);
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(addressapi));
HttpResponseMessage response = httpClient.SendRequestAsync(request).AsTask().Result;
jsonFile = response.Content.ToString();
httpClient.Dispose();
return 0;
}
catch (Exception ex)
{
jsonFile = ex.Message;
return (int)ex.HResult;
}
}
示例13: FetchData
public static async Task<JsonObject> FetchData(string token)
{
var httpClient = new HttpClient();
var teamInfoURL = BASE_URL + Uri.EscapeUriString(token);
var teamInfoURI = new Uri(teamInfoURL);
var teamInfoStr = await httpClient.GetStringAsync(teamInfoURI);
httpClient.Dispose();
JsonObject teamInfoObject;
if (!JsonObject.TryParse(teamInfoStr, out teamInfoObject))
{
// Error :(
throw new Exception("Couldn't parse JSON object.");
}
if (!teamInfoObject.GetNamedBoolean("ok"))
{
// Error :(
throw new Exception("Request was not successful.");
}
return teamInfoObject.GetNamedObject("team");
}
示例14: sendGetRequest
//public static string preServiceURI = "http://52.11.206.209/RESTFul/v1/";
//public static string preServiceURI = "http://54.68.126.75/RESTFul/v1/";
public static async Task<string> sendGetRequest(string methodName)
{
Random r = new Random();
int x = r.Next(-1000000, 1000000);
double y = r.NextDouble();
double randomNumber = x + y;
string ServiceURI = preServiceURI + methodName + "?xxx=" + randomNumber.ToString();
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(ServiceURI);
request.Headers.Authorization = Windows.Web.Http.Headers.HttpCredentialsHeaderValue.Parse(Global.GlobalData.APIkey);
//request.Headers.Authorization = Windows.Web.Http.Headers.HttpCredentialsHeaderValue.Parse("ce1fb637b7eee845c73b207d931bbc10");
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string returnString = await response.Content.ReadAsStringAsync();
response.Dispose();
httpClient.Dispose();
request.Dispose();
return returnString;
}
示例15: FetchChannels
public async Task FetchChannels()
{
var httpClient = new HttpClient();
var channelsURL = CHANNELS_URL + Uri.EscapeUriString(Token);
var channelsURI = new Uri(channelsURL);
var channelsStr = await httpClient.GetStringAsync(channelsURI);
httpClient.Dispose();
JsonObject channelsObject;
if (!JsonObject.TryParse(channelsStr, out channelsObject))
{
throw new Exception("Couldn't parse JSON object.");
}
if (!channelsObject.GetNamedBoolean("ok"))
{
throw new Exception("Request was not successful.");
}
var channelsArray = channelsObject.GetNamedArray("channels");
Channels = new ObservableCollection<SlackChannel>();
foreach (var channel in channelsArray)
{
Channels.Add(new SlackChannel(channel.GetObject()));
}
}