I want to make a POST request to a rest service. There is no authentication, it has only two customized header. My code is below. I am getting the error :
An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code.
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"
May you help ? What is wrong in the code ?
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("id", "8888");
client.DefaultRequestHeaders.Add("type", "CUSTOMER");
Uri uri = new Uri(requestUri);
var ob = new { id= "5", color= "pink" };
var transferJson = JsonConvert.SerializeObject(ob);
var content = new StringContent(transferJson, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;
Your code itself doesn't look faulty. The error message suggests that the request ran into a timout, which means that the HttpClient waits for a set period of time and terminates if the server doesn't respond. Have you tried pinging the server to make sure it's actually up and running?
It that's the case you could try to increase the timeout value of your HttpClient (see here https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=netframework-4.8).
Additionally you could try to send the request with another tool like Postman to see whether the issue lies within your code, your parameters (like timeout), or the server itself.
Related
I have errors after call webapi from Windows Service
first error is :
An error occurred while sending the request.
second error is :
The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel.
You could use System.Net.Http.HttpClient.. You will obviously need to edit the fake base address and request URI in the example below but this also shows a basic way to check the response status as well.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8888/");
//Usage
HttpResponseMessage response = client.GetAsync("api/importresults/1").Result;
if (response.IsSuccessStatusCode){var dto = response.Content.ReadAsAsync<ImportResultDTO>().Result;}
else{Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);}
My ASP.NET web app is interacting with an API and making calls to various endpoints.
When I hit the endpoints through Postman it's quick and successful. When I run the app locally it also works as expected. However, when I publish the app to Azure I'm having issues hitting the API and it's very inconsistent.
Sometimes it works and sometimes it doesn't. When it fails the call will hang up for a few seconds and then I get the following exception:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
What I've come to notice through trial-and-error is that if I wait for around 10 seconds or so after each request it works. I tried using Thread.Sleep(10000) and Task.Delay(10000) to simulate me waiting the 10 seconds but those are causing issues (receiving the same connection attempt failed error).
using (HttpClient client = new HttpClient())
{
//Construct POST Request
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, Global.api + "/token");
req.Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
//Do POST Request
using (HttpResponseMessage response = await client.SendAsync(req, HttpCompletionOption.ResponseContentRead))
{
using (HttpContent content = response.Content)
{
//Store data retrieved from POST request
string strContent = await content.ReadAsStringAsync();
Token token = await content.ReadAsAsync<Token>();
}
}
}
Thread.Sleep(10000);
I'm using Pipedream as a data source which provides event data via an SSE API.
As per the instructions here, I'm using the following code to subscribe to the SSE:
var client = new ServerEventsClient("https://api.pipedream.com/sources/dc_mXugEA/sse")
{
EventStreamRequestFilter = req => req.AddBearerToken("[MYTOKEN]"),
OnMessage = message => Console.WriteLine(message.Json)
}.Start();
However, I get a System.Net.WebException with the message 'The remote server returned an error: (404) Not Found.'
But if I use HttpClient directly, it succeeds:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "[MYTOKEN]");
using var reader = new StreamReader(await client.GetStreamAsync("https://api.pipedream.com/sources/dc_mXugEA/sse"));
while (!reader.EndOfStream)
{
Console.WriteLine($"Received message: {await reader.ReadLineAsync()}");
}
Of course, I want to use ServerEventsClient instead of HttpClient to avoid the boilerplate looping code. But why is ServerEventsClient not working in this case?
ServiceStack’s Server Events clients only works with ServiceStack’s Server Events feature, I.e. it can’t be used to consume a 3rd Party SSE stream.
I've found with the below code that on any second httpclient request, I always get a 400 Bad Request.
I can confirm the API calls actually work and return a 200 - so if I flip them, the first call will return 200 second call, 400.
I can't figure out why this is the case.
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage blah = await client.GetAsync("api/subscriptions?account=eclipse&application=Sample");
HttpResponseMessage dfds = await client.GetAsync("api/subscriptions?account=eclipse");
...
}
It's hard to tell without seeing the controller function you're trying to call. What's probably happening is that the REST service is experiencing an exception on the server and is throwing back a 400.
What web server is the service using? Maybe it has some sort of simultaneous request blocking. You could try not using async.
What I would do is open up Fiddler (http://www.telerik.com/fiddler) and look at the network traffic. Look at the response from the web server and see if there is any exception data there.
I am trying to send a HTTP GET request to a service secured with BASIC authentication and https. If I use the RESTClient Firefox plugin to do so there is no problem. I am defining the basic-header and sending the GET to the url and I am getting the answer (data in json).
Now I am working on a Windows Store App in C# which is meant to consume the service. I enabled all required capabilities in the manifest and wrote the following method:
private async void HttpRequest()
{
string basic = "Basic ...........";
Uri testuri = new Uri(#"https://...Servlet");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", basic);
Task<HttpResponseMessage> response = client.GetAsync(testuri);
var text = await response;
var message = text.RequestMessage;
}
I tried out many different possibilites like getting the response-string but everything lead to an 401 Status Code answer from the Server.
I looked at many similar problems and my understanding of the communication is the following: Client request -> Server response with 401 -> Client sends Authorization header -> Server response with 200 (OK)
What I don't understand is why I am getting the 401 "Unauthorized" Status Code although I am sending the Authorization header right at the beginning. It would be interesting if someone knows how this is handled in the RESTClient.
The BASIC header is definetly correct I was comparing it with the one in the RESTClient.
It would be great if someone could help me with this.
Thanks in advance and kind regards,
Max
Was having a similar problem, i added a HttpClientHandler to HttpClient.
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("","")
var httpClient = new HttpClient(httpClientHandler);
Credentials should be encoded, before adding to the header. I tested it in WPF app, It works...
string _auth = string.Format("{0}:{1}", "username", "password");
string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));
string _basic = string.Format("{0} {1}", "Basic", _enc);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization",_basic);