本文整理汇总了C#中HttpClient.GetStringAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.GetStringAsync方法的具体用法?C# HttpClient.GetStringAsync怎么用?C# HttpClient.GetStringAsync使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpClient
的用法示例。
在下文中一共展示了HttpClient.GetStringAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
}
示例2: GetFacebookPagePosts
async void GetFacebookPagePosts()
{
HttpClient client = new HttpClient();
string token = await client.GetStringAsync(new Uri("https://graph.facebook.com/oauth/access_token?client_id=364363933754883&client_secret=7d72f56490cf8b0a7075a99cb791037f&grant_type=client_credentials"));
var posts = await client.GetStringAsync(new Uri("https://graph.facebook.com/ZSCOfficial/posts?limit=15&access_token=" + token.Split('=')[1]));
var FbPosts = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(posts);
//myGridview.ItemsSource = FacebookPosts.data;
FacebookPosts = new List<Datum>(FbPosts.data);
}
示例3: GetChannel
public async Task<IEnumerable<M3uStream>> GetChannel( string aChannelName )
{
using( var theHttpClient = new HttpClient() )
{
var theAccessTokenJson = JsonObject.Parse( await theHttpClient.GetStringAsync( TokenRequestUri( aChannelName ) ) );
var theTokenJson = JsonObject.Parse( theAccessTokenJson.GetNamedString( "token" ) );
var theStream = StreamRequestUri( aChannelName, theTokenJson, theAccessTokenJson.GetNamedString( "sig" ) );
var theM3uData = await theHttpClient.GetStringAsync( theStream );
return M3uStream.ParseM3uStreams( theM3uData, theStream );
}
}
示例4: LoadMoreAlbumList
public async Task<List<Album>> LoadMoreAlbumList(int page = 1)
{
if (Info == null)
return null;
string link;
if (page <= 1)
link = Info.Remove(Info.Length - 4) + "playlist.html";
else
link = Info.Remove(Info.Length - 4) + "playlist." + page + ".html";
string response;
using (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"));
response = await hc.GetStringAsync(new Uri(link, UriKind.Absolute));
}
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(response);
var divtag = (from divtags in hdoc.DocumentNode.Descendants("div").Where(x => x.Attributes[0].Value == "fram_select")
select divtags).First();
var albumList = from litag in divtag.ChildNodes[4].ChildNodes.Where(x => x.Name == "li")
select new Album()
{
Cover = litag.ChildNodes[1].ChildNodes[1].ChildNodes[3].ChildNodes[0].Attributes["src"].Value,
Title = litag.ChildNodes[3].ChildNodes[1].ChildNodes[0].InnerText,
Link = litag.ChildNodes[3].ChildNodes[1].ChildNodes[0].Attributes["href"].Value,
Artist = litag.ChildNodes[3].ChildNodes[3].ChildNodes[0].InnerText
};
return albumList.ToList();
}
示例5: dajSveKorisnike
public async void dajSveKorisnike()
{
//primjer servis povlacenja svih korisnika, isti princip kao i FourSquare, koristi se isti Http api
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(new Uri(serviceHost + uposleniciName));
JsonValue value = JsonValue.Parse(response);
}
示例6: GetStory
private async void GetStory(Uri story_uri)
{
try
{
HttpClient client = new HttpClient();
Uri uri = (Uri)story_uri;
string data = await client.GetStringAsync(uri);
JsonObject json_story = JsonObject.Parse(data);
string html = json_story.GetNamedString("body").Replace("<div class=\"headline\">\n\n<div class=\"img-place-holder\"></div>\n\n\n\n</div>", "");
string css = json_story.GetNamedArray("css")[0].ToString().Replace("\"", "");
#region Get story css
//TODO Get story css
html = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + css + "\" /></head>" + html + "</html>";
#endregion
this.wv.NavigateToString(html);
}
catch (Exception)
{
this.wv.NavigateToString("<body><h>No story!!!</h></body>");
}
}
示例7: GetChannels
public async Task<StreamSearchResults> GetChannels( string aGame, uint aOffset, uint aSize )
{
using( var theHttpClient = new HttpClient() )
{
return new StreamSearchResults( JsonObject.Parse( await theHttpClient.GetStringAsync( StreamsListUri( aGame, aOffset, aSize ) ) ) );
}
}
示例8: GetGames
//----------------------------------------------------------------------
// PUBLIC ITwitchQueryService
//----------------------------------------------------------------------
public async Task<GameSearchResults> GetGames( uint aOffset, uint aSize )
{
using( var theHttpClient = new HttpClient() )
{
return new GameSearchResults( JsonObject.Parse( await theHttpClient.GetStringAsync( GamesListUri( aOffset, aSize ) ) ) );
}
}
示例9: OnNavigatedTo
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//string id = "";
string id = string.Empty;
if (NavigationContext.QueryString.TryGetValue("id", out id))
{
System.Diagnostics.Debug.WriteLine("ID de la pieza: " + id);
}
HttpClient client = new HttpClient();
string json = await client.GetStringAsync(new Uri("http://museosapp.azurewebsites.net/Piezas/"+id));
_piezas = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Piezas>>(json);
//Piezas piezas = NavigateServiceExtends.GetNavigationData(NavigationService) as Piezas;
//System.Diagnostics.Debug.WriteLine("PIEZAAAAAAA: " + piezas.descripcion);
//piezas.descripcion;
//Ésta línea trae toda la información del museo que se ha seleccionado en otro xaml.
// Y la muestra en el xaml actual.
//this.DataContext = piezas;
ElementosQR.ItemsSource = _piezas;
loadPieza.Visibility = Visibility.Collapsed;
txtCargando.Visibility = Visibility.Collapsed;
}
示例10: GetParaphrases
public async static Task<JsonArray> GetParaphrases(string sentence, int maxParaphrases)
{
string urlTemplate = "http://api.microsofttranslator.com/v3/json/paraphrase?sentence={0}&language={1}&category={2}&maxParaphrases={3}";
string url = string.Format(urlTemplate, sentence, "en-us", "general", maxParaphrases);
AdmAuthentication admAuth = new AdmAuthentication(
"61ac4bbd-ceea-4cd2-a33e-26ac7644f516",
"I7kv+trhQqTDI9egay1fwTgXG0URzMnb4m4kURzov5k=");
AdmAccessToken token = await admAuth.GetAccessToken();
string responseContent = string.Empty;
using (HttpClient client = new HttpClient())
{
try
{
var headers = client.DefaultRequestHeaders;
headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", token.access_token);
responseContent = await client.GetStringAsync(new Uri(url));
}
catch (Exception ex)
{
responseContent = ex.Message;
}
}
var obj = JsonObject.Parse(responseContent);
JsonArray paraphrases = obj.GetNamedArray("paraphrases");
return paraphrases;
}
示例11: GetResultsForQuery
public static async Task<ObservableCollection<WebResult>> GetResultsForQuery(string query) {
string queryParams = "Web?Query=%27" + query + "%27&$format=json";
string searchUri = BING_SEARCH_URI + queryParams;
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;
filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(searchUri, "empty", BING_SEARCH_API_KEY);
JsonArray jsonResults;
using (var client = new HttpClient(filter))
{
string response = await client.GetStringAsync(new Uri(searchUri));
JsonObject obj = JsonObject.Parse(response);
jsonResults = obj.GetNamedObject("d").GetNamedArray("results");
}
var results = new ObservableCollection<WebResult>();
for (var i = 0; i < jsonResults.Count; i++) {
var obj = jsonResults.GetObjectAt((uint)i);
string articleText = "";
results.Add(new WebResult(
obj.GetNamedString("ID"),
obj.GetNamedString("Title"),
obj.GetNamedString("Description"),
obj.GetNamedString("Url"),
articleText
));
}
return results;
}
示例12: GetRepositoriesAsync
public async Task<GithubQueryResult<Repository>> GetRepositoriesAsync(string query, int pageIndex = 1)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (query.IsBlank())
{
throw new ArgumentException("Github query could not be empty.", nameof(query));
}
if (pageIndex <= 0)
{
throw new ArgumentOutOfRangeException(nameof(pageIndex));
}
string queryEncoded = WebUtility.UrlEncode(query);
string url = string.Format("https://api.github.com/search/repositories?q={0}&page={1}&per_page={2}&order=desc", queryEncoded, pageIndex, PAGE_SIZE);
string json;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240");
json = await client.GetStringAsync(new Uri(url));
}
return JsonConvert.DeserializeObject<GithubQueryResult<Repository>>(json);
}
示例13: HttpClient_ClientUsesAuxRecord_Ok
public async Task HttpClient_ClientUsesAuxRecord_Ok()
{
X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate();
var server = new SchSendAuxRecordTestServer(serverCert);
int port = server.StartServer();
string requestString = "https://localhost:" + port.ToString();
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
var tasks = new Task[2];
tasks[0] = server.RunTest();
tasks[1] = client.GetStringAsync(requestString);
await Task.WhenAll(tasks).TimeoutAfter(15 * 1000);
if (server.IsInconclusive)
{
_output.WriteLine("Test inconclusive: The Operating system preferred a non-CBC or Null cipher.");
}
else
{
Assert.True(server.AuxRecordDetected, "Server reports: Client auxiliary record not detected.");
}
}
}
示例14: RetrieveFeed
public async Task<Series> RetrieveFeed(string feedAddr)
{
string content = string.Empty;
using (HttpClient client = new HttpClient())
content = await client.GetStringAsync(feedAddr);
var feed = XElement.Parse(content);
var id = feed.Element(ChannelElementName).Element(LinkElementName).Value;
var title = feed.Element(ChannelElementName).Element(TitleElementName).Value;
var imagePath = feed.Element(ChannelElementName).Element(ImageXName).Attribute(HrefElementName).Value;
var imageElement = feed.Element(ChannelElementName).Element(ImageElementName);
if (imageElement != null)
imagePath = imageElement.Element(UrlElementName).Value;
var description = feed.Element(ChannelElementName).Element(DescriptionElementName).Value;
var rVal = new Series
{
Id = id,
Title = title,
ImagePath = imagePath,
Description = description
};
var items = feed.Element(ChannelElementName).Elements(ItemElementName);
await rVal.SetEpisodes(Task.Run(() => ParseEpisodes(items)));
return rVal;
}
示例15: GetAlbumInfo
public async Task<Album> GetAlbumInfo(string albumTitle, string artistName)
{
try
{
var deezerClient = new HttpClient();
string json = await deezerClient.GetStringAsync(new Uri(string.Format("http://api.deezer.com/search/album?q={0} {1}&appid={2}", albumTitle, artistName, MusicMDFetcher.DeezerAppId)));
if (json == "{\"data\":[],\"total\":0}")
{
return null;
}
var deezerAlbums = JsonConvert.DeserializeObject<Albums>(json);
if (deezerAlbums.Data != null)
{
var deezerAlbum = deezerAlbums.Data.FirstOrDefault();
var album = new Album();
album.MapFrom(deezerAlbum);
return album;
}
}
catch (Exception e)
{
Debug.WriteLine("DeezerClient.GetAlbumInfo", e);
}
return null;
}