I have a thread class which makes a web request. After 20-30 urls request, its throwing exception: System.Web.HttpException: Request timed out.
My code is below where it is throwing exception:
httpReq.AllowAutoRedirect = false;
httpReq.KeepAlive = false;
httpReq.Headers.Add("Location", "");
httpReq.Timeout = this.HttpRequestTimeout;
httpRes = (HttpWebResponse)httpReq.GetResponse();
In last line : httpRes = (HttpWebResponse)httpReq.GetResponse();
it is throwing exception.
"The remote server returned an error: (403) Forbidden."
I am using session for setting some values with the request header.
I got the answer. I was not using httpRes.close() method after using response object. That's why after 80-90 request it was returning : "The remote server returned an error: (403) Forbidden ".
Related
I send following http request:
http://localhost:8081/member/createCompany/getSmallThumbnail/
On server side I hit into controller method:
#RequestMapping("/error")
public String error(Model model, HttpServletRequest request){
if(request.getRequestURI().contains("thumbnail")){
System.out.println("thumbnail accepted");
}
request.toString();
model.addAttribute("message", "page not found");
return "errorPage";
}
At this method I want to know url with which the request arrived.
If in debug I stop inside this method I see information needed for me:
But I cannot find method in request which will return this.
Please help to return url which I want.
P.S.
Actually I have not mapped controller in my spring mvc application(url is broken) for http://localhost:8081/member/createCompany/getSmallThumbnail/. This url("/error") configured in web.xml as error page.
Your request got redispatched to /error (presumably for error processing).
If this framework follows the normal Servlet error dispatching behavior, then your original request can be found in the HttpServletRequest.getAttributes() under the various javax.servlet.RequestDispatcher.ERROR_* keys.
ERROR_EXCEPTION - The exception object
ERROR_EXCEPTION_TYPE - The type of exception object
ERROR_MESSAGE - the exception message
ERROR_REQUEST_URI - the original request uri that caused the error dispatch
ERROR_SERVLET_NAME - the name of the servlet that caused the error
ERROR_STATUS_CODE - the response status code determined for this error dispatch
What you want is
String originalUri = (String) request.getAttribute(
RequestDispatcher.ERROR_REQUEST_URI)
This HttpHandler does not send a response if con.Open() throws an exception, for example if faultyConnectionString has an invalid database name. Why?
public void ProcessRequest(HttpContext context)
{
int status = 400;
string message = "Test error!";
string faultyConnectionString = "Data Source=LOCALHOST\\SQLEXPRESS;Initial Catalog=XXX;User ID=XXX;Password=XXX";
try
{
using (SqlConnection con = new SqlConnection(faultyConnectionString))
{
//throw new Exception("This works as expected, and is returned to client");
con.Open();
}
}
catch (Exception ex)
{
status = 500;
message = "Test Exception: " + ex.Message;
}
context.Response.StatusCode = status;
context.Response.StatusDescription = message;
}
Here is how I am handling the call in the client:
function GetContacts() {
$.ajax({
type: "POST",
url: "xxx.ashx",
data: "",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text", // "json",
success: function (response, a, b) {
alert(response.status + " " + response.statusText);
},
error: function (response, a, b) {
alert(response.status + " " + response.statusText);
}
});
}
If I F12 in FireFox it shows me that there is no Response received after the request is sent. In IE it shows me "SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.". In both cases the jquery ajax call returns status=0 and statusText="error".
If I comment out the two lines inside the catch block then it works as expected, sending the 403 code to the client and ignoring the exception.
Different types of exceptions do not have the same problem. If I throw a new Exception() before con.Open() then it also works as expected. What is different with SqlException?
UPDATE: The very first time I hit ProcessRequest it gets called 5 times in succession before the client shows the status=0 result (breakpoint on first line is hit 5 times).
FIDDLER: If I fire up Fiddler it (fiddler) intercepts the transaction and sends "504 Fiddler - Receive Failure" to my ajax call. Looks like the initial repetition may be a retry mechanism, when fiddler is active it does it 13 times.
Fiddler reports: "Session #xxx raised exception System.Net.Sockets.SocketException An existing connection was forcibly closed by the remote host".
I believe the way your client (browser) handles 404 errors is what is causing this, and each browser type is handling the error differently. 404 errors are specific to "Not Found" so you may want to use a different error code such as a 500 error. More info on error codes is available here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Please keep in mind that passing back detailed error messages to a client could be a security issue due to information leakage. You may be better off passing back a generic error to the client and logging detailed error information on the server side.
Edit:
Testing this locally, the way you are setting context.Response.StatusDescription to contain ex.Message is producing an invalid HTTP response. Try only placing text such as Internal Server Error in there. Additional details can be added to the body of the response using context.Response.Write(bodyText) but please keep the security implications of this in mind.
I am getting an error called Exception type: EmptyPartException error. My work is after the message is sent to the sendPort successfully, send an email. The Orchestration used is,
The ConstructMessage_3 constructs, SucessMessage which refers to the Multipart message SuccMsg which is of type System.Xml.XmlDocument.
Under Message_Assignment I have
SuccEmailPort(Microsoft.XLANGs.BaseTypes.Address) = "mailto:abc#gmail.com";
SucessMessage.SuccEmail = MsgVariable;
SucessMessage(SMTP.CC) = "abc#xyz.org";
SucessMessage(SMTP.Subject) = "Employee Feed";
SucessMessage(SMTP.From) = "BizTalk#sample.com";
SucessMessage(SMTP.EmailBodyText) = "The Upload Failed";
SucessMessage(SMTP.MessagePartsAttachments) = 1;
SucessMessage(SMTP.SMTPHost) = "smtp.mycompany.org";
SucessMessage(SMTP.SMTPAuthenticate) = 0;
SucessMessage(SMTP.EmailBodyTextCharset)="UTF-8";
SucessMessage.SuccEmail(Microsoft.XLANGs.BaseTypes.ContentType) = "text/plain";
SucessMessage.SuccEmail(MIME.FileName) = "emp.txt";
Here MsgVariable refers to the Variable whose type is System.Xml.XmlDocument. When tried to send the message, the message is received but not the email. It shows me error like,
xlang/s engine event log entry: Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'ErrorHandling.Orchestration_1
The service instance will remain suspended until administratively resumed or terminated.
If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
InstanceId:
Shape name: Send_3
ShapeId:
Exception thrown from: segment 2, progress 14
Inner exception: The part 'SuccEmail' of message 'SucessMessage' contains zero bytes of data.
Exception type: EmptyPartException
Am I doing the process right or is there any other way for doing this. What is the mistake I did here. Any help would be greatly appreciated.
In the expression shape add
SucessMessage = new System.Xml.XmlDocument();
I've got the following server code:
var server = new Server("http://localhost:13170/");
server.MapConnection<EchoConnection>("echo");
server.Start();
But when I connect to it from my client code:
var connection = new Connection("http://localhost:13170/echo");
connection
.Start()
.ContinueWith(t =>
{
if (!t.IsFaulted)
connection.Send("Hello");
else
Console.WriteLine(t.Exception);
});
...it reports:
System.Net.WebException: The remote server returned an error: (404) Not Found.
What am I doing wrong?
Turns out that the parameter to MapConnection must start with a slash:
server.MapConnection<EchoConnection>("/echo");
This is because Server.ResolvePath prepends a slash before looking up the URL in the mappings.
I am using Httconnection for connecting to webserver , somtimes request fails causing
EOFException when calling httpconnection.getResponseCode().
I am setting the following headers while making the connection
HttpConnection httpconnection = (HttpConnection) Connector.open(url.concat(";interface=wifi"));
httpconnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
httpconnection.setRequestProperty("Content-Language", "en-US");
I am closing all the connections after processing the request properly.Is this exception is due to exceeding max connections.
It's an internal server error, which return status code 500 in response.
This may be caused by incorrect request, but as well server code or overload may be the reason.
If you have access to server, check event logs.
See also
500 EOF when chunk header expected
Why might LWP::UserAgent be failing with '500 EOF'?
500 EOF instead of reponse status line in perl script
Apache 1.3 error - Unexpected EOF reading HTTP status - connectionreset
Error 500!
UPDATE On the other hand, if it's not response message, but a real exception, then it may be simply a bug, just like in old java
And workaround may be putting getResponseCode() inside of try/catch and call second time on exception:
int responseCode = -1;
try {
responseCode = con.getResponseCode();
} catch (IOException ex1) {
//check if it's eof, if yes retrieve code again
if (-1 != ex1.getMessage().indexOf("EOF")) {
try {
responseCode = con.getResponseCode();
} catch (IOException ex2) {
System.out.println(ex2.getMessage());
// handle exception
}
} else {
System.out.println(ex1.getMessage());
// handle exception
}
}
Talking by connections number limit, read
What Is - Maximum number of simultaneous connections
How To - Close connections
Using HTTPTransportSE, write this before invoke the method "call"
ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
transport.call(SOAP_ACTION, envelope, headerPropertyArrayList);