The remote server returned an error: (500) Internal Server Error. - URL created by IBM ICN - httpwebrequest

I am creating a console application in C# to check if URL is up and running using HttpWebRequest.
Note that the URL is generated by IBM's ICN (IBM Content Navigator). It is NOT hosted using IIS.
I am receiving the below error while trying to get HttpWebResponse from my C# console application.
Message: "The remote server returned an error: (500) Internal Server Error."
Status: ProtocolError
Below code is not working:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(myurl);
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";
request.Accept = "text/plain";
request.ContentType = "text/plain;charset=UTF-8";
request.Headers.Add("Accept-Language", "en-US");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
//Do some operations
}
else
{
//Do some operations
}
}
Please let me know if additional info. is required.
Any help or suggestions to solve this issue are appreciated.
Thanks in advance.

Related

C# Web API call return a 401.1 only when it's long-running

I have a Web API method that is secured by Windows Authentication. Here's the client code:
var uri = new Uri(#"https://myapi.mysite.com/api/method");
var request = HttpWebRequest.Create(uri);
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "application/json";
request.Timeout = 30 * 60 * 1000;
request.Credentials = new NetworkCredential("userName", "password", "domain");
using (var response = request.GetResponse())
{
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(responseStream.ReadToEnd());
}
}
When https://myapi.mysite.com/api/method takes less than about 5 minutes to return, all is well. As soon as it takes 5 minutes or longer (5 minutes seems to be a magic number), I start getting a 401 back. I'm using the same credentials both times. Everything is the same except the amount of data the server is processing (obviously more data leading to longer processing time).
The specific 401 I'm getting is the '401 - Unauthorized: Access is denied due to invalid credentials.' message.
I've experimented with KeepAlive, CredentialCache, setting a server timeout and many other options/approaches and can't get anything to work.
The server is IIS 7.5 running under a service account whose password never expires.
Any help would be appreciated.

Create a new calendar from CalDav API

I am trying to create a new calendar in my principal's home folder using SabreDav.
I couldn't find how to achieve this - is it even possible ?
UPDATE:
I found out about MKCALENDAR method, but the following returns an "abandoned" request error:
<C:mkcalendar xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav" xmlns:ical="http://apple.com/ns/ical/" >"
<D:set>
<D:prop>
<D:displayname>cal Display Name</D:displayname>
<ical:calendar-color>cal Color</ical:calendar-color>
</D:prop>
</D:set>
</C:mkcalendar>
Sending it with a HttpWebRequest fails with a canceled request messgage...
Thanks in advance!
UPDATE 2:
Some more details:
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create("http://my.sabredavcalendar.srv/calendarserver.php/calendars/admin/my_new_calendar/");
Request.Method = "MKCALENDAR";
Request..Credentials = new NetworkCredentials("usr", "pwd");
Request.ContentType = "application/xml";
string body = "<C:mkcalendar [.....] </C:mkcalendar>";
Request.ContentLength = body.Length;
// ---
// The using block throws an error...
using (Stream reqStream = Request.GetRequestStream()) {
byte[] encodedBody = Encoding.UTF8.GetBytes(body);
reqStream.Write(encodedBody, 0, encodedBody.Length);
reqStream.Close();
}
Response = (HttpWebResponse)Request.GetResponse();
The error message I get is
The request was aborted: The request was canceled
On the server side, here is the access log:
192.168.1.200 - - [06/Jul/2015:09:51:48 +0200] "MKCALENDAR /calendarserver.php/calendars/admin/my_new_calendar/ HTTP/1.1" 400 25 "-" "-"
The error log is empty... so it seems I get a "bad request" response which is not caught when preparing the request?!
UPDATE 3: the body contains special characters as "éàê..." which is why the contentlength part was wrong !
I take hnh's comment as an answer: the problem was indeed the Request.ContentLength = body.Length.
Corrected code is:
Request.ContentLength = Encoding.UTF8.GetByteCount(body);

HttpWebRequest - (500) Internal Server Error

I have a SOAP Envelop logged in Database using IDispatchMessageInspector. I need to invoke my WCF Service having wsHttpBinding using the SOAP Envlope.
I am using below code to invoke my WCF Service.
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("ServiceURL");
req.Method = "POST";
string reqBody = theBomRequest; //it has entire soap
byte[] reqBodyBytes = Encoding.UTF8.GetBytes(reqBody);
req.ContentType = "application/soap+xml; charset=utf-8";
req.GetRequestStream().Write(reqBodyBytes, 0, reqBodyBytes.Length);
req.GetRequestStream().Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
if (resp.ContentLength > 0)
{
Console.WriteLine(new StreamReader(resp.GetResponseStream()).ReadToEnd());
}
resp.Close();
At GetResponse, I'm getting (500) Internal Server Error
Thanks,
Akif
Enable Tracing on your Service and see what is the cause for exception.

how to keep connection live while using httpwebrequest?

I am using httpwebrequest and httpwebresponse to send request and get response respectively.
For some reason my connection gets closed before the response is recieved.
Here is my code :
WebRequest webRequest = WebRequest.Create (uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes (parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write (bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show ( ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader (webResponse.GetResponseStream());
return sr.ReadToEnd ().Trim ();
}
catch (WebException ex)
{
MessageBox.Show ( ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
return null;
}
Error :
By default, if you are using HTTP/1.1 protocol, then the connection is assumed to be kept alive, unless the server decides to indicate otherwise (with a Connection: close header).
In your case, you are having a server refusing the request with a 500 error. You should investigate why that is happening. You shouldnt worry about the connection:close header at this point. Even if the server closes the connection, the client will handle that gracefully by opening a new connection the next time.
To summarize, the 500 response from the server is not due to the connection being closed. It is because the server does not like the request you sent.
If it is session timeout error(I cannot see the error message), you should have configuration parameter like below in your web server or J2EE server.
Below is from tomcat web.xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>

Post SOAP Envelope to WCF service

I have the following SOAP message that i want to post it to my WCF Service and get response.
"<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">\r\n <s:Header>\r\n <a:Action s:mustUnderstand=\"1\">http://schemas.devleap.com/OrderService/IOrderService/InsertOrder</a:Action>\r\n <a:MessageID>urn:uuid:4cb619b7-365b-4108-880f-b302029d03c2</a:MessageID>\r\n <a:ReplyTo>\r\n <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>\r\n </a:ReplyTo>\r\n </s:Header>\r\n <s:Body>\r\n <InsertOrder xmlns=\"http://schemas.devleap.com/OrderService\">\r\n <order xmlns:d4p1=\"http://schemas.devleap.com/OrderService/Order\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n <d4p1:IdCustomer>2</d4p1:IdCustomer>\r\n <d4p1:IdOrder>46</d4p1:IdOrder>\r\n <d4p1:OrderItems xmlns:d5p1=\"http://schemas.devleap.com/OrderService/OrderItems\" xmlns:d5p2=\"http://schemas.devleap.com/OrderService/OrderItem\">\r\n <d5p1:OrderItem>\r\n <d5p2:IdProduct>P01</d5p2:IdProduct>\r\n <d5p2:Quantity>5</d5p2:Quantity>\r\n <d5p2:EuroPrice>20</d5p2:EuroPrice>\r\n </d5p1:OrderItem>\r\n <d5p1:OrderItem>\r\n <d5p2:IdProduct>P01</d5p2:IdProduct>\r\n <d5p2:Quantity>5</d5p2:Quantity>\r\n <d5p2:EuroPrice>20</d5p2:EuroPrice>\r\n </d5p1:OrderItem>\r\n </d4p1:OrderItems>\r\n </order>\r\n </InsertOrder>\r\n </s:Body>\r\n</s:Envelope>"
How can i post this SOAP to the WCF service?
I tried this but i get "The remote server returned an error: (500) Internal Server Error." exception.
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/soap+xml; charset=utf-8");
var response = client.UploadString("http://localhost:8000/OrderService", data);
}
If i remove the header from Envelope and add:
client.Headers.Add("Content-Type", "application/soap+xml; charset=utf-8");
client.Headers.Add("SOAPAction", "\"http://schemas.devleap.com/OrderService/IOrderService/InsertOrder\"");
i get the same error.
If i put
client.Headers.Add("Content-Type", "text/xml; charset=utf-8");
i get exception that server expects "application/soap+xml; charset=utf-8".
If someone knows how to call it right please help.
Thank you,
Adrya
After more digging i managed to post the SOAP to the service.
Here is code:
WebClient myWebClient = new WebClient();
myWebClient.Headers.Add("Content-Type", "application/soap+xml; charset=utf-8");
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
byte[] responseArray = myWebClient.UploadData("http://localhost:8000/OrderService", "POST", byteArray);
Console.WriteLine("\nResponse received was {0}", Encoding.ASCII.GetString(responseArray));
Console.ReadKey();