I am trying to send request to http://localhost/apptfg/get_biography_group?nombre_grupo=fondoflamenco which is a php based webservice that access to mysql database and retrieve information about the group but I always get a 404 not found when I execute the application in my windows phone 8 device, however when I debug the url in fiddler I get the right result which must be {"success":1,"group":[{"nombre_grupo":"fondoflamenco","anyo_creacion":"2006","descripcion":"Fondo Flamenco Flamenco is a group formed by three young Sevillian. Astola Alejandro Soto, Antonio Sanchez and Rafael Ruda M.R","musicos":"Rafael Ruda,Antonio Manuel Rios,"}]}
this is the HttpClient code I use in my application:
public async Task<string> makeHttpRequest(string group_name)
{
var resultstring = String.Empty;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "text/html");
try
{
resultstring = await client.GetStringAsync(new Uri("http://localhost/apptfg/get_group_biography.php?nombre_grupo=" + group_name));
client.Dispose();
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
return resultstring;
}
Related
I have a UWP app written in C#.
For some specific users (i.e. specific PCs), the app is not able to perform HTTP requests.
Those PCs are not under any VPN, they turned off any firewall or antivirus, they tried with several connections (e.g. home router, phone hotspot, public wifi, etc.), always with the same result.
Opening a browser and browsing to
https://ltbackend.azurewebsites.net/diagnostic/ping
they are able to see the correct page (actually, a plain text "OK").
But if they use the app (which performs an HTTP GET call using C#), this one fails.
This is the code in C# that we use:
string pingUrl = "https://ltbackend.azurewebsites.net/diagnostic/ping";
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, pingUrl);
using (HttpClient httpClient = new HttpClient())
{
try
{
using (HttpResponseMessage response = await httpClient.SendAsync(req))
{
string stringRes = await response.Content.ReadAsStringAsync();
HttpStatusCode respCode = response.StatusCode;
// .... our biz logic with stringRes and respCode...
}
}
catch (HttpRequestException e)
{
// the ping request for those users throws this exception...
// the error message is "An error occurred while sending the request."
}
}
But if they use the app (which performs an HTTP GET call using C#), this one fails.
I have run your code within UWP platform, it could work well and return 'ok' string. But it looks you used HttpClient under System.Net.Http namespace, and it often used in cross-platform, such as xamarin app.
For sending get request within UWP, we suggest you use Windows.Web.Http.HttpClient. The following is simple get method you could refer to.
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
//Add a user-agent header to the GET request.
var headers = httpClient.DefaultRequestHeaders;
//The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
Uri requestUri = new Uri("https://ltbackend.azurewebsites.net/diagnostic/ping");
//Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = string.Empty;
try
{
//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
For more info please refer HttpClient document.
If you are using latest version of .NET try once using WebClient instead of HttpClient.
Ref: https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadstringasync?view=net-5.0
string pingUrl = "https://ltbackend.azurewebsites.net/diagnostic/ping";
var client = new WebClient();
string stringRes = await client.DownloadStringTaskAsync(pingUrl);
If I put this URL in a browser, the list of my RabbitMQ bindings is displayed:
http://guest:guest#127.0.0.1:6004/api/bindings
However, I get a 401 (unauthorized) if I use that same URL with HttpClient:
private void RemoveOldBindings(IModel channel, string exchangeName)
{
HttpClient client = new HttpClient();
string url = "http://guest:guest#127.0.0.1:6004/api/bindings";
try
{
HttpResponseMessage response = client.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
// remaining code here
}
catch (Exception ex)
{
// We always hit this exception block with a 401 error
Debug.WriteLine(ex.Message);
}
}
My RMQ log file shows that the user was authenticated, but apparently not authorized? Why?
$ docker logs fff8766052a2 | tail -10
2021-06-24 17:54:12.326 [info] <0.8127.0> connection <0.8127.0> (172.18.0.1:52312 -> 172.18.0.2:5672): user 'guest' authenticated and granted access to vhost '/'
There is a comment, here, that the guest user can only connect to localhost:
https://stackoverflow.com/a/37281517/279516
So I tried replacing 127.0.0.1 in the URL with localhost, but still get a 401.
Looks like I needed to set the auth header instead of just relying on including it in the URL.
private void RemoveOldBindings(IModel channel, string exchangeName)
{
HttpClient client = new HttpClient();
// Notice the credentials are gone from the URL
string url = "http://localhost:6004/api/bindings";
try
{
// This was the fix
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($"guest:guest")));
HttpResponseMessage response = client.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
// remaining code here
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
I am writing a program to check check if a Voucher number is Valid and I am finding it difficult to extract the Error Message from a REST API which I am working with.
C# is pretty new to me as normally VB.net but covering for someone at the moment.
Basically I have a HttpWebReqest and HttpWebResponse objects and using the below code I am making a successful request and getting a response just fine.
When everything goes well there are no problems, but for example if a voucher was invalid or the site was invalid I should get a response saying this, as I do in Postman, see below for example.
{
"message": "The given data was invalid.",
"errors": {
"voucher_no": [
"Sorry, that voucher number is invalid."
]
}
}
Instead I get thrown to the Try/Catch.. with the Exception
Error Message Error 422 unprocessable entity,
with no further details or object to check for the real message above?
try
{
using (HttpWebResponse response = mywebrequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
// I am unable to get to this part of the Code to process the Error because Try/Catch is executed instead ...
}
else
{
Stream dataStream1 = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream1);
responseFromServer = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
msgbox = new MsgBox_UI("Error", "Web Server Returned an Error", "There is a problem with this Voucher. It may be Expired or invalid at this time.", 1, false, 28);
msgbox.ShowDialog();
break;
}
If any one out there has any ideas as to how I can get this working it would be a great help.
This is by design, GetResponse will throw a WebException (1) when the request returns an 'unsuccessful' status code.
You can check the Status property on the WebException to get the statuscode
and the Response property for the response of the webserver.
The first thing it's better to use HttpClient class instead.
this code should work for you (if not let me know) :
private async Task<string> GetExtensionToken()
{
string url = "https://YourApi.com";
try
{
var httpclient = new HttpClient();
using (HttpResponseMessage response = httpclient.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
string Is_Not_Valid = "invalid";
if (result.Contains(Is_Not_Valid))
{
string token = "Whatever you want to extract if error page" ;
return token;
}
else
{
string token = "Whatever you want to extract if succeeded" ; return token;
}
}
}
}
catch (Exception ex)
{
return "Error from catch ";
}
}
Usage:
private async void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = await GetExtensionToken();
}
Ok so I took the advice of Peter above and decided to use HttpClient().
However I actually went with Restharp and installed the Nuget Package RestSharp into my Project. (Main reason is POSTMAN Code Snippet gave me the exact code to use.
Then it worked like a dream.
I am not doing it Async so here is what I found fixed my problem after adding
using RestSharp;
var client = new RestClient("https://api.voucherURL.uk/redeem");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Smart-Auth", "sk_xxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", "{\n \"voucher_no\":\"JY584111E3\",\n \"site_id\": 14\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I'm attempting to get a list of orders for my Xamarin Form application from my rails api.
Here is the code in my Xamarin Application that returns a "406":
async void UpdateOrders(string token)
{
// clear all the previous orders
orders.Clear();
var client = new HttpClient();
string url = "http://localhost:3000/api/orders?access_token=" + token;
Debug.WriteLine(url);
var response = await client.GetAsync(url);
//response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
Debug.WriteLine("this didn't work");
//var ex = CreateExceptionFromResponseErrors(response);
//throw ex;
}
else
{
// get the orders from the JSON
var orderItems = JsonConvert.DeserializeObject<List<Order>>(response.ToString());
// add all the orders to the page
orders = new ObservableCollection<Order>(orderItems);
}
}
url = "http://localhost:3000/api/orders?access_token=03642494d1631421a8b49a21085b53907e8498794c0dcacc61c7b4eefbf1b7eb"
** on a side-note the CreateExceptionFromResponseErrors line throws an error?
The same url above returns the following when I run it in CURL:
[{"id":1,"invoice":"HALP","description":"TESTING","weight":100.0,"length":48,"width":48,"height":48,"account_id":1,"driver_id":null,"status":"preview","account_quote":576,"driver_quote":432,"created_at":"2017-03-11T17:18:40.418Z","updated_at":"2017-03-11T17:18:40.418Z","driver_rating":5,"account_rating":5,"guid":"cfd12c84-b260-440c-a21a-7a8aab44b5ac"}]
Where am I going wrong?
HTTP 406 is the code for "not acceptable", meaning that your HttpClient is not properly configured to receive the payload from the server. You will need to configure your header for the correct content type.
See also:
What is “406-Not Acceptable Response” in HTTP?
So, I know it's possible to ping a server, with Ping.Send(string) in c#, but would it be possible to ping a specific web application, instead of the whole server. For example, there is a server with three websites (a, b, and c) hosted on it. The server IP is 1.1.1.1. Each of the websites has a different port. How would I check to see if website a is currently being hosted?
Just make a request to WebSite
private bool PingWebSite(string url)
{
try
{
WebRequest.Create(url).GetResponse();
return true;
}
catch
{
return false;
}
}
And then use it
var isWebSiteWorking = PingWebSite("http://stackoverflow.com");
I wouldnt do the GetResponse() because, what if that particular Url is returning you a 1+ GB of file, this will block your application. Just making the head request should be sufficient or using TcpClient.
async Task<Boolean> IsAvailable()
{
string url = "http://www.google.com";
try
{
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
response.Dump();
return true;
}
else
{
return false;
}
}
}
catch (Exception ex)
{
return false;
}
}