How to get Location in Response Header use HttpResponseMessage in windows phone - httprequest

I want get Location in Response Header but i can't see this in Response. How to get this. Please help me.
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
FormUrlEncodedContent postData = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("background","1"),
new KeyValuePair<string,string>("line1","Content1"),
new KeyValuePair<string,string>("line2","Content2")
});
HttpResponseMessage response = await client.PostAsync("URL", postData);
string rp = await response.Content.ReadAsStringAsync();

Related

HttpClientFactory increased response time with high load

I am connecting to SOAP web service and I am using HttpClientFactory. Application is running on docker. Tester were testing load test with jmeter. After putting more and more load on application response time was increasing forom 100 ms to 50 sec. They have tried Soap service directly and it is performing ok.
var _client = _httpClientFactory.CreateClient("Servis");
var request = new HttpRequestMessage(
HttpMethod.Post,
"")
{
Content = new StringContent(soapRequest, Encoding.UTF8, "text/xml")
};
_client.DefaultRequestHeaders.ConnectionClose = true;
StringContent httpContent = new StringContent(soapRequest, Encoding.UTF8, "text/xml");
using var response = await _client.PostAsync(_client.BaseAddress, httpContent);
var stream = await response.Content.ReadAsStreamAsync();
var content = await _streamHelper.StreamToStringAsync(stream);
if (response.IsSuccessStatusCode)
return content;
throw new ApiException
{
StatusCode = (int)response.StatusCode,
Content = content
};
But I have tried RESTSharp and I have same problem
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
var postUrl = _configuration["OibSettings:BaseAddress"];
IRestClient client = new RestClient();
client.ConfigureWebRequest((r) =>
{
r.ServicePoint.Expect100Continue = false;
r.KeepAlive = false;
});
IRestRequest request = new RestRequest
{
Resource = postUrl,
Method = Method.POST
};
request.AddHeader("Content-Type", "text/xml");
request.AddHeader("Accept", "text/xml");
request.AddParameter("text/xml", soapRequest, ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
return response.Content;
throw new ApiException
{
StatusCode = (int)response.StatusCode,
Content = response.Content
};
It starts working OK but after some time response time start to increse and. Around 5% of responses have extreme time response compared to targeted 100 ms on response.
Also some requests are timeouting and end up in error. But directly jmiter on that service it is ok.

xamarin.forms ,Foursqaure api response is not displaying but works in postman and foursqaure site after providing api key ?where im wrong

private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?

TestHost generating Invalid URI: The format of the URI could not be determined

I have written some integration tests using Microsoft.AspNetCore.TestHost, But when I try to get a message as Invalid URI.
I can create TestServer successfully and able to create a client. But when I call an API using the client it says invalid URI. The URL created by TestHost is http://localhost/ and there is nothing look wrong in that URL.
I am not able to understand how could this URL be wrong. There is no other localhost website running in my machine also.
When I run my web API it's run on this URL Http:\localhost:5000 and set that as base address in my test project but it still throws the same error.
This my code to build Test Server
public MongoDbFixture()
{
var builder = new WebHostBuilder()
.UseContentRoot(GetContentRootPath())
.UseEnvironment("Test")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(GetContentRootPath())
.AddJsonFile("appsettings.Test.json")
.Build())
.UseStartup<Startup>(); // Uses Start up class from your API Host project to configure the test server
_testServer = new TestServer(builder);
Client = _testServer.CreateClient();
//Client.BaseAddress = new Uri("http://localhost:5000/");
AuthClient = _testServer.CreateClient();
//AuthenticateClient();
//AddPromptQuestions();
//SetupGoogleTranslationService();
}
This is a code to make a request.
public async Task<string> GetToken()
{
try
{
if (string.IsNullOrEmpty(token))
{
//var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "kunal.ahmedabad#gmail.com"), new KeyValuePair<string, string>("password", "Password123!") });
var content = new StringContent("{email:'test#test.com',password:'Integration#85'}", Encoding.UTF8, "application/json");
var response = await Client.PostAsync(new Uri("api/Accounts/Login"), content).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
//var token = await response.Content.ReadAsAsync<OkResult>();
var newToken = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var tokenResponse = JsonConvert.DeserializeAnonymousType(newToken, new { Token = "", IsPhoneNumberConfirmed = "" });
token = tokenResponse.Token;
//token = newToken.Split(":")[1].Replace("\"", "").Replace("}", "");//todo:add better logic to read token.
return token;
}
}
catch (Exception)
{
}
return "";
}
I am not sure what is a valid URL, but this setup was working earlier.
Try changing:
new Uri("api/Accounts/Login")
To:
new Uri("api/Accounts/Login", UriKind.Relative)

POST with Restsharp doesn't work as expected

I have the following code:
var Client = new System.Net.WebClient();
var Response = Client.UploadString("myurl", PostData);
it works as expected
I am trying to do the same with Restsharp:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddBody(PostData);
var Response = client.Execute(request);
doesn't work, and:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", PostData);
var Response = client.Execute(request);
doesn't work either...
what am I missing?

ReasonPhrase: 'Forbidden' HttpResponseMessage winrt

i'm getting this error :ReasonPhrase: 'Forbidden' in the response variable:
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();
besides i used it with an other url and it works fine ! any ideas please?