The code goes below
public static async Task<string> getForwardUrl(string url)
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage forwardRequest = new HttpRequestMessage();
forwardRequest.RequestUri = new Uri(url);
HttpResponseMessage Message = await client.SendAsync(forwardRequest);
return Message.RequestMessage.RequestUri.OriginalString;
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
//...
}
When I run this in a uwp project, exception occurs. The message of this exception shows that the redirection request would change the safe connection to an unsafe one(After that , I checked the URL of the login page , It's https ,but the page after I logged in is http).
I find a similar question, he recommends using Windows.Web.Http instead of System.Net.Http but I get the same error message.
Thanks for your reply
EDIT:
The URL is: https://tinyurl.com /57muy (remove the space) or short a http url with tinyurl.com! The problem only occurs with a shortet http side!
Error: An error occurred while sending the request. Innermessage: Error message not found for this error
According to your description, I'd suppose you are developing a UWP app. And as you've mentioned, we got the exception here because the redirection request would change the safe connection to an unsafe one. To solve this problem, we can turn off auto-redirect and do the redirection by ourselves.
For example:
public static async Task<string> getForwardUrl(string url)
{
var handler = new System.Net.Http.HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new System.Net.Http.HttpClient(handler);
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.Redirect || response.StatusCode == System.Net.HttpStatusCode.Moved)
{
return response.Headers.Location.AbsoluteUri;
}
return url;
}
Related
I have made a website to check if it is still working or not, on my machine it works normally but when I publish it on the server, it gives error 500. I looked at the article on microsoft and saw "Don't use WebRequest or its derived classes for new development. Instead, use the System.Net.Http.HttpClient class."
But I don't know how to use that method. How do I change the method of my website?
And this is my code:
public static bool WebRequestTest(string url)
{
try
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
System.Net.WebResponse myResponse = myRequest.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
And this is my error:
Server Error in '/' Application. Invalid URI: The format of the URI could not be determined. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UriFormatException: Invalid URI: The format of the URI could not be determined.
You can do like below code
public static async Task<bool> WebRequestTest(string url)
{
try
{
using (var client = new HttpClient())
{
var result = await client.GetAsync(url);
HttpStatusCode httpStatusCode= result.StatusCode;
}
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
You will get lot of example about Httpclient.
Hey guys,
I have a problem with my code. Since about a week my code is not working anymore without any changes. I am pretty sure, that my could should work. All I get is Error 404: forbidden.
Below is a snippet of my Code. I also read about adding a header of the webclient, which did not help. Any other suggestions? I am sorry if my syntax is not that good, it is my first post on stackoverflow.
Thanks in advance!
string epicId = "ManuelNotManni";
WebClient webClient = new WebClient();
Uri uri = new Uri("https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/");
string result = String.Empty;
try
{
string website = $"{uri.ToString()}{epicId}?";
result = webClient.DownloadString(website);
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
webClient.Dispose();
}
This is the exact error:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.Net.WebClient.GetWebResponse(WebRequest request)
at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream)
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at TestProject.Program.Main(String[] args) in > C:\Users\Manue\source\repos\TestProject\Program.cs:line 17
You're right. Your code should work fine.
Issue is that URL you're requesting which is actually:
https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/ManuelNotManni?
This returns a 403 status code in any case - no matter if you use a browser, your code or for example postman.
I suggest to have a look at the response body while using postman.
It shows this
<html class="no-js" lang="en-US">
<!--<![endif]-->
<head>
<title>Attention Required! | Cloudflare</title>
<meta name="captcha-bypass" id="captcha-bypass" />
Tracker.gg wants API users to register their apps with them before they're given access to the API.
What you need to do is to first head to their Getting Started page. Here you will have to create an app, which should give you an authentication key.
When you have done this, you want to change your code slightly to add the Authentication Header. Like so for example:
var webClient = new WebClient();
webclient.Headers.Add("TRN-Api-Key", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
As a sidenote, WebClient has been deprecated and it's recommended to use HttpClient from now on. Here's your code with HttpClient instead:
var epicId = "ManuelNotManni";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("TRN-Api-Key", "YOUR API KEY GOES HERE");
// Simplifying Uri creation:
var uri = new Uri($"https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/{epicId}");
var result = string.Empty; // C# prefers lowercase string
try
{
var response = await httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
Console.WriteLine($"Unable to retrieve data for {epicId}.");
Console.WriteLine($"Statuscode: {response.StatusCode}");
Console.WriteLine($"Reason: {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
httpClient.Dispose();
}
This happens when we violate the Firewall rule set by Cloudflare, you can visit this blog for more details.
https://community.cloudflare.com/t/community-tip-fixing-error-1020-access-denied/66439
I use xamarin forms to create an mobile app for Android and iOS. I need to make Http Request, so I use HttpClient.
Here is a simple code of request :
var client = new HttpClient();
try
{
string requestUrl = URL_DATABASE + "xxx";
var content = new StringContent("{\"param\":\"" + param+ "\"}", Encoding.UTF8, "application/json");
var response = await client.PostAsync(requestUrl, content);
if (response.StatusCode == HttpStatusCode.OK)
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
return "{\"status\":-1}";
}
catch (Exception ex) // Error catched : "the request timed out"
{
return "{\"status\":-1}";
}
I used Postman to check result of my request and work's well, I got good response without timeout.
I noticed that error occurs sometimes but can last an hour.
error : the request timed out
Thank you in advance for your help
I have swagger URL http://somehost/swagger/index.html
end methods there as shown on image:
As someone said to me http://somehost/api/Referral/GetReferralByNumber is API address which I can refer it by HTTP request.
static void Main(string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
string result = client.DownloadString("http://somehost/api/Referral/GetReferralByNumber");
}
catch (System.Net.WebException ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
this is code for testing API, but
System.Net.WebException: The remote server returned an error: (404)
Not Found exception
is thrown. any help?
Client.DownloadString() makes an GET request. Your action supports POST. Try to use HttpClient, it should be better for your case.
You are hitting a Get Request and for Get request there is no such endpoint.
You should try adding the HTTP option Post to the server.
Code:
private static readonly HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/referral/GetReferralByNumber", data);
Where data is the data which should be posted to the server.
You should create an http client and use POST like this:
var method = HttpMethod.Post;
var endPoint = "http://somehost/api/Referral/GetReferralByNumber";
var request = new HttpRequestMessage(method, endPoint);
var client = new HttpClient();
var response = await httpClient.SendAsync(request);
I am calling UploadStringTaskAsync on a restful Web API 2 post method I wrote and it is failing with no exceptions. If I change the call to be UploadString, it works as expected. I've tried a number of different approaches. With UploadStringTaskAsync attempt Fiddler does show the post being issued but with a content-length mismatch (see below). I am running this call from a class library included in a test console app. .Net 4.5.2 So far just running in debug mode from VS 2015. here's my code:
private async Task PostLoggingItem(SmgLoggingItem loggingItem)
{
try
{
//using (WebClient client = new WebClient())
//{
//WebClient client = new WebClient();
const string authToken = "mytoken";
loggingItem.AuthToken = Encryptor.GenerateSecurityToken(authToken);
client.Encoding = Encoding.UTF8;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
//client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("user","mypwd","mydom");
// set content type to JSon
client.Headers.Add("Content-Type", "application/json");
var jsonItem = JsonConvert.SerializeObject(loggingItem);
var response = await client.UploadStringTaskAsync(new Uri(ConfigurationManager.AppSettings["WebLogAPI"]), jsonItem);
//string response = client.UploadString(new Uri(ConfigurationManager.AppSettings["SMGWebLogAPI"]), "POST", jsonItem);
string result = JsonConvert.DeserializeObject<string>(response);
if (result != "ok")
{
await SMTPSendEmailAsync.SendEmail("brownp#spectrummg.com", "logging failed WebAPI call",
"Error return from WebAPI call in PostLoggingItem");
}
return;
//}
}
catch (Exception e)
{
await SMTPSendEmailAsync.SendEmail("brownp#spectrummg.com", "logging failed WebAPI call",
"Exception in PostLoggingItem" + e.Message);
return;
}
}
You can see where I have commented out the working UploadString call. Also, I have a theory problem related to "lifetime" of the WebClient object, so played around with creating it in the method (see commented using), but now create it with the object instantiation to which method PostLoggingItem belongs.
here's fiddler:
I'd sure like to know why the Async does not work. Also, I have used aync methods and awaits all the way up the call tree - to no avail.