我有一个PCL,WP和WinStore项目。在PCL项目中,我有一个使用此方法的类:
private async Task<string> GetIpAddress()
{
const string url = "http://www.ip-adress.com/";
const string buscar = "<h3>Your IP address is:";
var client = new HttpClient();
var data = await client.GetStringAsync(url);
if (data.IndexOf(buscar, StringComparison.Ordinal) <= -1) return;
var IpAddress = data.Remove(0, data.IndexOf(buscar, StringComparison.Ordinal) + buscar.Length + 1);
IpAddress = IpAddress.Remove(IpAddress.IndexOf("</h3>", StringComparison.Ordinal));
return IpAddress;
}
当我在Windows Phone项目上调用该方法时,该方法运行正常,但不在Windows应用商店项目中。相反,我收到此错误消息:
答案 0 :(得分:9)
看来你需要凭据并指向api,这就是为什么它的“Forbiden”
尝试将其称为浏览器:来自另一个问题“HttpClient Request like browser”
void Main()
{
GetIP("http://www.ip-adress.com/");
}
async void GetIP(string url){
try{
"Looking Up".Dump("OK");
var x = await GetResponse(url);
x.Dump();
}
catch(Exception e){
e.Dump("Problems:");
}
}
private static async Task<string> GetResponse(string url)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
var response = await httpClient.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode();
using (var responseStream = await response.Content.ReadAsStreamAsync())
//using (var decompressedStream = new System.IO.Compression.GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(responseStream))
{
return streamReader.ReadToEnd();
}
}
//注意:我注释了压缩,