HttpWebRequest timeout issue after couple of calls - httpwebrequest

Below code is throwing a timeout exception after couple of calls (5 or 10 calls), it works fine always when I'm running fiddler in my machine.
I read some answers here that if it's working when the fiddler is on then that means it could be a proxy issue, but how it's working some times? I've tried setting a timeout value more than the default value, still it fails.
HttpWebRequest requiredRequest = CreateRequestWithEmptyBody(url);
requiredRequest.ContentType = "application/xml";
try
{
requestStream = requiredRequest.GetRequestStream();
requestStream.Write(requestBodyData, offset: 0, count: requestBodyData.Length);
requestStream.Flush();
}
catch (WebException exc)
{
}
finally
{
requestStream.Close();
}

Typically, this means that you forgot to call .Close() on the HTTPResponseStream that you pulled from the HttpWebRequest object.
I discuss this here: http://www.telerik.com/automated-testing-tools/blog/eric-lawrence/13-02-28/help-running-fiddler-fixes-my-app.aspx

Related

got 'CancellationException: Request execution cancelled' always when throwing an exception in httpasyncclient callback

I use HttpAysnClient to do http requests, and I found when I throw an exception in the failed callback, the next request always be failed, how to fix it?
I use maven dependency: 'org.apache.httpcomponents:httpasyncclient:4.1.5'.
my java test code:
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
AtomicBoolean fireException = new AtomicBoolean(false);
while (true) {
try {
String url;
if (fireException.compareAndSet(false, true)) {
url = "http://localhost:8080"; // throw Connection refused
} else {
url = "http://www.apache.org/";
}
final HttpGet request2 = new HttpGet(url);
httpclient.execute(request2, new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response2) {
System.out.println("completed, " + request2.getRequestLine() + "->" + response2.getStatusLine());
}
public void failed(final Exception ex) {
System.out.println("failed, " + request2.getRequestLine() + "->" + ex);
throw new RuntimeException();
}
public void cancelled() {
System.out.println(request2.getRequestLine() + " cancelled");
}
});
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
TimeUnit.SECONDS.sleep(1);
}
}
} finally {
httpclient.close();
}
exception in the next requests: java.util.concurrent.CancellationException: Request execution cancelled
I can confirm same behavior with version 4.1.5.
I must confess it is quite surprising to see an application uncontrolled exception shutting down the whole client unexpectedly. In the context of an application reusing same client instance in multiple places, means the application client gets completely unsuable, with catastrophic consequences for the service.
You can use the "isRunning" method to evaluate if the client is under this situation, and potentially try to recreate the client again. But it is definately incovenient to see the client being shutdown like this.
After exercising the client with different conditions (error responses, slow responses...), the only way to reproduce this is to point to an invalid endpoint where no server is running. This is the condition presented in the original example.
I think I found the issue here https://jar-download.com/artifacts/org.apache.httpcomponents/httpasyncclient/4.1.5/source-code/org/apache/http/impl/nio/client/InternalIODispatch.java
You can see onException doesn't have a try/catch block to properly handle exceptions from the application.
I have confirmed this issue is fixed in Httpclient5 5.1.3. So other than fixing your application code to avoid uncontrolled exceptions, the solution is to migrate into the new Httpclient5 lib version.
you can see doc in https://hc.apache.org/httpcomponents-client-5.1.x/migration-guide/migration-to-async-simple.html
and if you want to use CloseableHttpClient you must start it client.start();

Web service Soap getting Read Timeout Exception

I am trying to create soap web service client by one client WSDL file by using Apache Axis 2 and tomcat 6.
I successfully generated client, but when I am calling methods to get data I am getting error.
WSDL location: https://staging2.myhcl.com/MedicalClaim/Service.svc?wsdl
Error:
Unable to sendViaPost to url[http://staging2.myhcl.com/MedicalClaim/Service.svc]
java.net.SocketTimeoutException: Read timed out
My doubt is mentioned below:
We are sending request with GET or POST methods that how we can know in SOAP web service?
When above mentioned error used to come?
Rather than Apache Axis 2, what other generating client can we use for this WSDL file?
You might need to check how much time it is taking at Skeleton end.I have done SOAP some time back and i have faced same issue.Below code might help you
private HttpURLConnection getConnection(String endPoint) {
try {
URL url = new URL(endPoint);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(20000); // 20 sec connection timeout
connection.setReadTimeout(60000); // 60 sec read timeout
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("POST");
OutputStream out = httpConnection.getOutputStream();
return httpConnection;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
But ensure that your service(Skeleton) is not taking much time to process the request.You can use SoapUI to find out how much time it is taking to return the response.Accordingly you can set the timeout value.
Here comes answers of your doubts:
1.You can set POST/GET in HttpURLConnection object.
2.The error specified can come if the connection is idle for long and the Service is not returning any result.Use SoapUI to check the reply from Service.
3.wsdl2java and java2wsdl with Apache Axis2 is a good option for this purpose.Also xmlbeans has an inbuilt converter, which is quite handy to use.

Get response and raw request when using proxies and resteasy client side framework 3.0.4

// Some setup steps
ResteasyProviderFactory factory = new ResteasyProviderFactory();
factory.registerProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);
Client client = ClientBuilder.newClient(new ClientConfiguration(factory));
WebTarget target = client.target(webappURL.toURI() + "api/v1");
resteasyWebTarget = (ResteasyWebTarget) target;
// the real request
MyApiController myApiController = resteasyWebTarget.proxy(MyApiController.class);
ClientResponse response = (ClientResponse) myApiController.doSomeStuff();
The code above works great, but I want to really know what is going on in terms of real http request and real http response when
myApiController.doSomeStuff();
is executed.
I am wondering what the best way is to catch and log the "raw" request and a catch and log the "raw" http response. I am only interested in solutions for resteasy-client 3.0.2.Final or similar...
Thanks!
Not sure how to get it if everything went well (response code 200), but in case the server returned anything else, a sub type of ClientErrorException which gives you access to the response / status code / entity (message body) etc is thrown.
try {
myApiController.doSomeStuff();
} catch (BadRequestException ce) {
// Handle
} catch (ClientErrorException e) {
MyErrorObject obj = ce.getResponse().readEntity(MyErrorObject.class);
// Handle
}

Openning Async WCF Service with wrong Username-Password hangs

I have a WCF service that implements the 'Custom-Username-Password-Validator'.
The service itself checks the username+password against a local file,
and if there is no match - it throws a FaultException with a message.
.
When I use the service synchronously it works fine.
When I go to work with it ASYNC, I have a problem.
If I pass the wrong 'Username+Password' credentials - and open the client,
instead of returning immediatly from the service going into my 'Channel_Faulted()' method,
the client thread simply waits until the Timeout triggers,
and then I get a 'TimeoutException'.
try
{
client = new MyServiceClient("WSDualHttpBinding_IMyervice");
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "bad password";
client.ChannelFactory.Faulted += new EventHandler(ChannelFactory_Faulted);
client.Open(); // This hangs for 01:00:00 minute
// Doesn't reach here
client.DoSomethingCompleted += new EventHandler<DoSomethingEventArgs(client_DoSomethingCompleted);
client.DoSomethingAsync(param);
}
catch (Exception ex)
{
// Enters here with a 'TimeoutException' exception
}
why does the client not trigger the 'Faulted' method I have ?
Why does it wait for a response from the service even though the service through a 'FaultException' during the 'Validate' method of the 'CustomUserNameValidator' ?
Sure, the code you are using appears to be missing 3 lines after your code line:
client.ChannelFactory.Faulted += new EventHandler(ChannelFactory_Faulted);
But again, I'm taking a shot in the dark since I've not made use of this option yet.
var local = client.ChannelFactory.CreateChannel();
((IClientChannel)local).Faulted += ChannelFaulted;
local.Open();
Better yet, the open method doesn't appear to be necessary according to the sample provide here: ChannelFactory
I personally have not used the ChannelFactory.Faulted event handler however, here is a post for your consideration: creating-wcf-channelfactory

Retrieve WCF Rest Response in Client

I'm using the WebChannelFactory<> to create a channel and interact with a WCF REST Service.
When there is an error, I want to retrieve the response from the channel to read the error message from the body of the response. But I cannot figure out how to get the response stream.
Here is my code:
using (var cf = new WebChannelFactory<T>(new Uri(url)))
{
var channel = cf.CreateChannel();
using (new OperationContextScope(channel as IContextChannel))
{
WebOperationContext.Current.OutgoingRequest.Headers
.Add("x-st-authtoken", HttpUtility.UrlDecode(Constants.General_AuthorizedToken));
WebOperationContext.Current.OutgoingRequest.Headers
.Add("x-st-tesskey", HttpUtility.UrlDecode(Constants.General_SessionKey));
try
{
a(channel);
}
catch (Exception ex)
{
throw new Exception("Status: " + ((int)WebOperationContext.Current.IncomingResponse.StatusCode).ToString());
}
}
}
In the catch statement, I want to include the data from the Response body...
It seems like an obvious thing, but I can't seem to find any information on the internet or anything.
Is there any specific reason for you to use ChannelFactory to interact with the REST service. I think it is easier to use HttpWebRequest object to invoke the REST service and there you can get the respone stream when an error is throw on the server.
Also check out RestSharp API through which you can achieve your task to read the response stream.
I believe it will throw a WebException.
so if you explicitly catch that type you can get use the WebException.Response property (which is an HttpWebReponse) on the exception and you can get the content from its stream.