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);
}
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 want to Pass XML string in HttpWebRequest Header?
my application in MVC4 .Net Framework 4.5 C#.
My code as below:
try
{
String requestXML = #"<REPORT>
<USER-DETAIL>
<NAME>ABC</NAME1>
<PASSWORD>12345</NAME2>
</USER-DETAIL>
</REPORT>";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.demoservice.com/service/getReport");
request.Accept = "application/xml";
request.Method = "POST";
request.Headers.Add("userId", "admin");
request.Headers.Add("password", "***");
request.Headers.Add("requestXml", requestXML);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
String output = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(output);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
But I'm getting the following error,
Specified value has invalid CRLF characters. Parameter name: value
Please help, thanks in advance.
Do not add arbitrary data to the request headers. POST data should go in the request body. Request headers must conform to the HTTP spec, which the data you're erroneously trying to stuff in there doesn't.
This is how you should be doing it:
var data = Encoding.UTF8.GetBytes(requestXML);
request.ContentType = "application/xml";
request.ContentLength = data.Length;
using (var body = request.GetRequestStream())
{
body.Write(data, 0, data.Length);
}
I am trying to update the title to a video, with an authorized put in C#:
string postUrl = "https://www.googleapis.com/youtube/v3/videos?part=snippet&access_token=" + this.access_token;
string postData = "id=" + this.videoID +
"&snippet[title]=" + Uri.EscapeDataString(status.Text) +
"&snippet[categoryId]=20";
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Timeout = 15000;
try
{
Stream putStream = request.GetRequestStream();
putStream.Write(postByte, 0, postByte.Length);
putStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
MessageBox.Show(err.Message);
}
The above code shows the following error:
The remote server returned an error: (400) Bad Request.
What am I doing wrong?
I figured it out. This particular endpoint needs a json responce, instead of a x-www-form-urlencoded response.
Help me please.
After sending post query i have webexception "Error getting response stream (ReadDone2): Receive Failure". help get rid of this error. thanks.
piece of code
try
{
string queryContent = string.Format("login={0}&password={1}&mobileDeviceType={2}/",
login, sessionPassword, deviceType);
request = ConnectionHelper.GetHttpWebRequest(loginPageAddress, queryContent);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//after this line //occurs exception - "Error getting response stream (ReadDone2): Receive Failure"
{
ConnectionHelper.ParseSessionsIdFromCookie(response);
string location = response.Headers["Location"];
if (!string.IsNullOrEmpty(location))
{
string responseUri = Utils.GetUriWithoutQuery(response.ResponseUri.ToString());
string locationUri = Utils.CombineUri(responseUri, location);
result = this.DownloadXml(locationUri);
}
response.Close();
}
}
catch (Exception e)
{
errorCout++;
errorText = e.Message;
}
//Methot GetHttpWebRequest
public static HttpWebRequest GetHttpWebRequest(string uri, string queryContent)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Proxy = new WebProxy(uri);
request.UserAgent = Consts.userAgent;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.AllowWriteStreamBuffering = true;
request.AllowAutoRedirect = false;
string sessionsId = GetSessionsIdForCookie(uri);
if (!string.IsNullOrEmpty(sessionsId))
request.Headers.Add(Consts.headerCookieName, sessionsId);
if (queryContent != string.Empty)
{
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] SomeBytes = Encoding.UTF8.GetBytes(queryContent);
request.ContentLength = SomeBytes.Length;
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
}
}
else
{
request.Method = "GET";
}
return request;
}
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
//try to add
newStream.Close();
}
In my case the server did not send a response body. After fixing the server, the "Receive Failure" vanished.
So you have two options:
Don't request a response stream, if you can live without it.
Make sure the server sends a response body.
E.g., instead of
self.send_response(200)
self.wfile.close()
the Python server code should be
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Thanks!\n")
self.wfile.close()
its not Xamarin or .NET's bug. :wink:
your server side endpoint fails when requesting. :neutral:
check your API endpoint if you own the api or contact support if you are getting API from third party company or service.
why it happens randomly : :wink:
because bug is in your inner if or loop blocks and it happens when it goes through this buggy loop or if.
best regards. :smile: