I have the following code:
string getCustomerTokenUrl = "someurl?vi=7&vt=" + encryptedToken + "&DPLF=Y";
HttpWebRequest objRequest = System.Net.HttpWebRequest.Create(getCustomerTokenUrl) as HttpWebRequest;
objRequest.AllowAutoRedirect = false;
try
{
HttpWebResponse response = objRequest.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.MovedPermanently)
{
Console.WriteLine(response.Headers["location"]);
}
}
catch (System.Net.WebException ex)
{
Console.WriteLine(ex);
}
When I run the code, I get a value from the location header, however it is missing an expected query string.
What I get:
http://anotherurl.com/api/SSO/autoSWLLoginCT
What I see in the chrome developer tools if I go directly to the url stored in getCustomerTokenUrl (in the response location header):
http://anotherurl.com/api/SSO/autoSWLLoginCT?ct=dabe6dcd25385b7a77e3a1587cef9e6fee20e7af0952a4691ef2169ef9ec6704367626a647c07473ec2b3c98746b79cc66a646857c85930042a616db69442ca5
Is there something I am configuring wrong that would cause the query string to be truncated?
Related
Postman returns some response JSON with HTTP status code 406 but my code which is written in C# returns the same HTTP status code error message but from Catch Block.
My Requirement is
The API I am consuming always returns some response JSON either the HTTP status code 200 or 400 or any other. When I test these API from post man it show response JSON but my code returns error when I execute the following line.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Here is my complete method.
private Dictionary<string, string> HTTPCall(CRMRequestData requestData, out bool isError, out string errorMessage)
{
isError = true;
errorMessage = "HTTPCall - initial error!";
try
{
ServicePointManager.SecurityProtocol = TLS12;
Dictionary<string, string> responseBag = new Dictionary<string, string>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestData.Uri);
request.Method = requestData.HttpMethodName;
request.ContentType = requestData.ContentType;
request.ContentLength = string.Format("{0}", requestData.Body).Length;
request.Headers.Add("x-api-key", requestData.APIKey);
if (requestData.Authorization != null)
{
request.Headers.Add("Authorization", string.Format("JWT {0}",requestData.Authorization));
}
if (requestData.HttpMethodName.ToUpper().Equals("POST"))
{
string body = requestData.Body;
Byte[] bytes = Encoding.UTF8.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//#Error at this line
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (responseData != null && responseData != "")
{
responseBag = ReadResponseJSON(responseData, requestData.CRMMethod, out isError, out errorMessage);
}
errorMessage = (!isError) ? "HTTPCall - API executed successfully!" : errorMessage;
return responseBag;
}
catch (Exception ex)
{
isError = true;
errorMessage = string.Format("{0}", ex.Message);
}
return null;
}
*Note: -
My code block works fine when API returns the HTTP status code 200 or 201
Try this:
What is "406-Not Acceptable Response" in HTTP?
In short: Add Accept header for the response (content type) returned by Service
I'm trying to check if .txt file is exists or not from web url. This is my code:
static public bool URLExists(string url)
{
bool result = false;
WebRequest webRequest = WebRequest.Create(url);
webRequest.Timeout = 1200; // miliseconds
webRequest.Method = "HEAD";
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)webRequest.GetResponse();
result = true;
}
catch (WebException webException)
{
//(url + " doesn't exist: " + webException.Message);
}
finally
{
if (response != null)
{
response.Close();
}
}
return result;
}
If i enter "http://www.example.com/demo.txt" is not a valid file path and website showing 404 error page then this code return true. How to solve this problem. Thanks in advance.
Use the StatusCode property of the HttpWebResponse object.
response = (HttpWebResponse)webRequest.GetResponse();
if(response.StatusCode == HttpStatusCode.NotFound)
{
result = false;
}
else
{
result = true;
}
Look through the list of possible status codes to see which ones you want to interpret as the file not existing.
while i am check URL using Web request and web Response method.
bool result = false;
try
{
if (!url.Contains("http://")) url = "http://" + url;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{ if (response.StatusCode == HttpStatusCode.OK) result = true; }
}
catch
{
return result;
}
return result;
But while i am check into this URL "http://payments.rctrustee.org/" am getting error. so i get the result is false. But i check into browser this URL is working.
i need this result true; how can i change my code.
Check with the following code:
try
{
if (!url.Contains("http://")) url = "http://" + url;
WebRequest req = WebRequest.Create(url);
WebResponse res = req.GetResponse();
Console.WriteLine("Url Exists");
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
if (ex.Message.Contains("remote name could not be resolved"))
{
Console.WriteLine("Url is Invalid");
}
}
I am trying to check if the url http://master.dev.brandgear.net is valid by the following method:
private bool UrlIsValid(string url)
{
using (var webClient = new WebClient())
{
bool response;
try
{
webClient.UseDefaultCredentials = true;
using (Stream strm = webClient.OpenRead(url))
{
response = true;
}
}
catch (WebException we)
{
response = false;
}
return response;
}
}
However, I am getting a web exception "404 not found.". I have checked the uri with Uri.IsWellFormedUriString and it is returning true. However, the same url can be opened through a browser. Any idea how to validate it?
I ran your example with following URL http://master.dev.brandgear.net and exception is also raised. If you open same URL in browser (for example Firefox) and run Firebug plugin, open Network tab you will see error 404 (Page not found). Your code is OK, but server returns 404.
To really get a response, you have to use WebException instead of GetResponse or GetResponseStream methods when the 404 exception happens.Also use HttpWebRequest and HttpWebResponse in these situations for better control,so after the exception occurs you check its state to see if its a ProtocolError and if so get the response from there:
private bool UrlIsValid(string url)
{
bool response = false;
HttpWebResponse rep = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
rep = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
if (we.Status == WebExceptionStatus.ProtocolError)
rep = (HttpWebResponse)we.Response;
}
if (rep != null)
{
try
{
using (Stream strm = rep.GetResponseStream())
{
response = true;
}
}
catch (WebException ex)
{
//no need variable is already false if we didnt succeed.
//response = false;
}
}
return response;
}
We have a url and we need to check whether web page is active or not. We tried following code:
WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(URL);
objRequest.Method = "HEAD";
try
{
objResponse = objRequest.GetResponse();
objResponse.Close();
}
catch (Exception ex)
{
}
Above code gave exception if unable to get a response but also works fine even if we have a "server error" on that page? Any help how to get server error?
The HttpResponse class has a StatusCode property which you can check. If it's 200 everything is ok.
You can change your code to this:
HttpWebResponse objResponse = null;
var objRequest = HttpWebRequest.Create("http://google.com");
objResponse = (HttpWebResponse) objRequest.GetResponse();
if(objResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("It failed");
}else{
Console.WriteLine("It worked");
}
For one thing, use a using statement on the response - that way you'll dispose of it whatever happens.
Now, if a WebException is thrown, you can catch that and look at WebException.Response to find out the status code and any data sent back:
WebRequest request = WebRequest.Create(URL);
request.Method = "HEAD";
try
{
using (WebResponse response = request.GetResponse())
{
// Use data for success case
}
}
catch (WebException ex)
{
HttpWebResponse errorResponse = (HttpWebResponse) ex.Response;
HttpStatusCode status = errorResponse.StatusCode;
// etc
}