I am trying to get a response from google in c# to get a token.
I am using the url - https://accounts.google.com/o/oauth2/token.
My code is the following;
public WebResponse GetResponse(string url, params GoogleParameter[] parameters)
{
//Format the parameters
string formattedParameters = string.Empty;
foreach (var par in parameters)
formattedParameters += string.Format("{0}={1}&", par.Name, par.Value);
formattedParameters = formattedParameters.TrimEnd('&');
//Create a request with or without parameters
HttpWebRequest request = null;
if (formattedParameters.Length > 0)
{
//string debug = (string.Format("{0}?{1}", url, formattedParameters));
request = (HttpWebRequest)WebRequest.Create(string.Format("{0}?{1}", url, formattedParameters));
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//Add the authentication header.
request.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
HttpWebResponse response = null;
//Get the response, validate and return
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
if (response == null)
throw new Exception("No Response from Google");
else if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("Incorrect Response: " + response.StatusCode + " " + response.StatusDescription);
return response;
}
The line
response = (HttpWebResponse)request.GetResponse();
is giving me the 405 Error Method Not Allowed.
I have tried for the past two days to fix this but nothing, can anyone see where I have went wrong?
Thanks
Related
I am writing some tests to ensure I am receiving a 200 status, even if no data is present. I am able to connect to the backend with my testing, but don't know how to read the data and then use the data in an Assert statement to confirm the status code is 200.
public void DataControllerTest_NoData(long dataId)
{
var uri = "http://localhost:8311/api/Data?columnId=";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + dataId);
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
try
{
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
}
catch (WebException we)
{
statusCode = ((HttpWebResponse)we.Response).StatusCode.ToString();
}
Assert.AreEqual(HttpStatusCode.OK, statusCode);
response.Close();
}
As I understand it, you want to find the status code if you see an error by adjusting your code with a small correction as shown below.
public void DataControllerTest_NoData(long dataId)
{
var uri = "http://localhost:8311/api/Data?columnId=";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + dataId);
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
}
catch (WebException we)
{
statusCode = ((HttpWebResponse)we.Response).StatusCode.ToString();
}
Assert.AreEqual(HttpStatusCode.OK, statusCode);
}
If you want to find the code of the exception text, use the following code
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
}
catch (WebException we)
{
string resultError = we.Message;
}
the catch is supposed to give me a 504 but for someone reason, I get a null on:
response = (HttpWebResponse)e.Response;
Below is my code:
var url = "http://www.go435345ogle.com";
HttpWebResponse response = null;
HttpStatusCode statusCode;
get http response
get status
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
//HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(keys.Value.Substring(0, keys.Key.Length - 1));
// Sends the HttpWebRequest and waits for a response.
response = (HttpWebResponse)myHttpWebRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("\r\nWebException Raised. The following error occured : {0}", e.Status);
response = (HttpWebResponse)e.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var sResponse = reader.ReadToEnd();
// Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
}
This is expected behaviour. Since domain www.go435345ogle.com doesn't exist, there is no server you could send request to, and therefore no response to receive. So WebException.Response simply returns null. Microsoft's docs clearly states, that WebException.Response returns:
If a response is available from the Internet resource, a WebResponse
instance that contains the error response from an Internet resource;
otherwise, null.
I have an strange problem. My .NET DataController send a response to an Java server (REST). All works fine, but when I send a response very often, suddenly the GetResponse method not coming back just hangs.
I don't know what's the problem is.
Here is my code
ServicePointManager.DefaultConnectionLimit = 20;
public string HttpGet(string url, string requestAccept)
{
if(string.IsNullOrEmpty(url))
throw new Exception("HttpGet: no REST service URL provided");
if(string.IsNullOrEmpty(requestAccept))
requestAccept = defaultRequestAccept;
if(!url.Equals("pc/alive"))
{
if(string.IsNullOrEmpty(SessionId))
{
if(string.IsNullOrEmpty(Authorization()))
throw new WebException("HttpGet: no login");
}
}
int tries = RestAccessData.MaxReconnect;
string result = string.Empty;
do
{
try
{
var request = NewWebRequest(url, "GET", false, true, requestAccept);
using(var response = request.GetResponse() as HttpWebResponse)
{
UpdateSessionId(response);
HttpStatusCode statusCode = response.StatusCode;
LOG.Debug("...StatusCode: {0} ({1})", (int) response.StatusCode, response.StatusDescription);
if((int) response.StatusCode < 500)
lastContactWithServer = DateTime.Now.Ticks;
switch(statusCode)
{
// Informational 1xx
case HttpStatusCode.Continue: // 100
case HttpStatusCode.SwitchingProtocols: // 101
throw new HttpResponseException(response);
// Successful 2xx
case HttpStatusCode.OK: // 200
result = ReadContent(response);
response.Close();
return (result);
case HttpStatusCode.NoContent: // 204 The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
response.Close();
return (string.Empty);
case HttpStatusCode.Created: // 201
case HttpStatusCode.NonAuthoritativeInformation: // 203
result = ReadContent(response);
throw new HttpResponseException(response, result);
case HttpStatusCode.Accepted: // 202 The request has been accepted for processing, but the processing has not been completed.
case HttpStatusCode.ResetContent: // 205 The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent.
case HttpStatusCode.PartialContent: // 206 The server has fulfilled the partial GET request for the resource.
throw new HttpResponseException(response);
case HttpStatusCode.Unauthorized:
throw new HttpResponseException(response);
default:
throw new HttpResponseException(response);
}
}
}
catch(WebException ex)
{
HandleWebException(ex);
}
catch(HttpResponseException ex)
{
throw ex;
}
catch(SystemException ex)
{
LOG.Error(ex, "caused a(n) {0}", ex.GetType().Name);
}
catch(Exception ex)
{
LOG.Warn(ex, "HttpGet: An error occured while trying to contact the server. Reason: {0}", ex.Message);
throw new UserException("An error occured while trying to contact the server.", ex);
}
}
while(0 < tries--);
return (string.Empty);
}
private HttpWebRequest NewWebRequest(string urlAsString, string requestType, bool withContentType, bool applicationJson, string requestAccept)
{
urlAsString = string.Format("{0}{1}", RestAccessData.GetUrl(), EncodeUrl(urlAsString));
Uri url;
if(!Uri.TryCreate(urlAsString, UriKind.Absolute, out url))
throw new NotSupportedException("url is not compatible");
LOG.Info("RESTUrl {0}", urlAsString);
try
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
if(!string.IsNullOrEmpty(SessionId))
{
CookieContainer cookies = new CookieContainer();
Cookie cookie = new Cookie
{
Name = "JSESSIONID",
Value = SessionId,
Domain = url.Host
};
cookies.Add(cookie);
request.CookieContainer = cookies;
}
request.Timeout = RestAccessData.Timeout;
request.Method = requestType;
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.KeepAlive = false;
request.ContentLength = 0;
request.Headers["Accept-Charset"] = "utf-8";
request.Accept = requestAccept;
request.UserAgent = LvsClient;
if(withContentType)
request.ContentType = applicationJson ? defaultApplicationJson : defaultApplicationWwwForm;
if(!string.IsNullOrEmpty(credential.UserName) && !string.IsNullOrEmpty(credential.Password))
request.Headers["Authorization"] = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", credential.UserName, credential.Password))));
return (request);
}
catch(Exception ex)
{
throw new UserException(TH.Translate("NewWebRequest caused an error"), ex);
}
}
Any ideas where the problem is?
This line is making me uncomfortable:
using(var response = request.GetResponse() as HttpWebResponse)
If the response is not an HttpWebResponse then it will never be disposed - the as operator will give you `null.
I found a solution. Very useful is this MSDN article about Understanding MaxServicePointIdleTime and DefaultConnectionLimit. After I play with MaxServicePointIdleTime property and read this comment
change the connection limit at any time
I found a good balance between connection alive and connection close. My client works fine after playing with MaxServicePointIdleTime and DefaultConnectionLimit.
I want to discover what causes a link to not work. Instead of not working, the link should show a particular message, like 404 or 403. How can I discover what HTTP status caused a given request to fail?
if (!IsLinkWorking(link))
{
//Here you can show the error. You don't specify how you want to show it.
TextBox2.ForeColor = System.Drawing.Color.Green;
TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
TextBox2.Text += string.Format("{0}\n working\n\n", link);
}
You need to use an HttpWebRequest. This will return you an HttpWebResponse, that has a StatusCode property - see the documentation here.
Here is an example:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK) {
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
There could be many reasons for not working links, you can try WebClient or HttpWebRequest / HttpWebResponse with proper HTTP header values to check whether link works or not.
Note that in case of 403, 404 etc. errors it throws exception which you should handle or else it will not give you the response status:
try{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
/* Set HTTP header values */
request.Method = "MethodYouWantToUse"; // GET, POST etc.
request.UserAgent = "SomeUserAgent";
// Other header values here...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
catch(WebException wex){
if(wex.Response != null){
HttpWebResponse response = wex.Response as HttpWebResponse;
if (response.StatusCode != HttpStatusCode.OK) {
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
}
}
Here is code I use to POST into RESTful web service. My problem is with a last line.
For example, my server can reply with different messages and same code.
Now, unless I get 200 OK I just get exception on last line.
I'd like to have better access to response header, etc no matter what code I got. How is that possible?
var request = WebRequest.Create(Options.DitatServerUri + Options.DitatAccountId + "/integration/trip") as HttpWebRequest;
if (request == null) return false;
request.ContentType = "application/json";
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Options.DitatLoginName + ":" + Options.DitatPassword)));
request.Method = "POST";
var serializer = new JavaScriptSerializer();
var serializedData = serializer.Serialize(trip);
var bytes = Encoding.UTF8.GetBytes(serializedData);
request.ContentLength = bytes.Length;
var os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
var response = request.GetResponse();
Example: I get WebException "Invalid Operation" but server actually send message with error explanation.
Building on what Jon said above in the comments, the exception thrown for a bad status code is most likely a WebException, which has Response and Status properties, as per this MSDN page. Therefore, you can get the response via:
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
Why not catch the exception and handle it appropriately?
try
{
var response = request.GetResponse();
}
catch (WebException webEx)
{
Console.WriteLine("Error: {0}", ((HttpWebResponse)webEx.Response).StatusDescription);
}