I am running the following code:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://10.0.0.22:8086/db/cadvisorDB/series?u=root&p=root&q=select%20max(memory_usage)%20from%20stats%20where%20container_name%20%3D%27execution_container_"+bench_list+"_"+i+"%27%20and%20memory_usage%20%3C%3E%200%20group%20by%20container_name");
//Thread.sleep(10000);
CloseableHttpResponse requestResponse = httpclient.execute(httpGet);
String response=EntityUtils.toString(requestResponse.getEntity());
System.out.println(response);
Output console:
[]
When I wait for the HttpResponse 30s it works. I got the complete response (JSON with data points) :
Thread.sleep(30000);
IS it possible using Apache Java client to tell the client to wait until getting a value different than "[]". I mean a non empty Json.
Using timeouts does not solve the problem.
Thank you in advance
Then setting the timeout will work.
HttpGet request = new HttpGet(url);
// set timeouts as you like
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(60 * 1000).setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000).build();
request.setConfig(config);
To be specific, no it is not possible simply using HttpClient "to tell the client to wait until getting a value different than" what it gets when the call is over. You have to program this yourself (in a loop or something.)
Does it make a difference if the sleep() is before HttpClients.createDefault() ?
Is it possible that your server at 10.0.0.22:8086 is just not ready when your code is executed? Is this server launched by the same app?
I had also same issue , but problem was 2 Http call making sequentially. so i have putted Thread.sleep(2000) for seconds and it worked.
Please confirm if your code making two rest call sequentially?
then may be you can place Thread.sleep just before second http call.
Related
We want to migrate all our apache-httpclient-4.x code to java-http-client code to reduce dependencies. While migrating them, i ran into the following issue under java 11:
How to set the socket timeout in Java HTTP Client?
With apache-httpclient-4.x we can set the connection timeout and the socket timeout like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
int timeout = 5; // seconds
HttpParams httpParams = httpClient.getParams();
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout * 1000);
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout * 1000);
With java-http-client i can only set the connection timeout like this:
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build()
But i found no way to set the socket timeout. Is there any way or an open issue to support that in the future?
You can specify it at the HttpRequest.Builder level via the timeout method:
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("..."))
.timeout(Duration.ofSeconds(5)) //this
.build();
httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
If you've got connected successfully but not able to receive a response at the desired amount of time, java.net.http.HttpTimeoutException: request timed out will be thrown (in contrast with java.net.http.HttpConnectTimeoutException: HTTP connect timed out which will be thrown if you don't get a successful connection).
There doesn't seem to be a way to specify a timeout on the flow of packets (socket timeout) on the Java Http Client.
I found an enhancement request on OpenJDK which seems to cover this possibility - https://bugs.openjdk.org/browse/JDK-8258397
Content from the link
The HttpClient lets you set a connection timeout (HttpClient.Builder) and a request timeout (HttpRequest.Builder). However the request timeout will be cancelled as soon as the response headers have been read. There is currently no timeout covering the reception of the body.
A possibility for the caller is to make use of the CompletableFuture API (get/join will accept a timeout, or CF::orTimeout can be called).
IIRC - in that case, it will still be the responsibility of the caller to cancel the request. We might want to reexamine and possibility change that.
The disadvantage here is that some of our BodyHandlers (ofPublisher, ofInputStream) will return immediately - so the CF API won't help in this case.
This might be a good thing (or not).
Another possibility could be to add a body timeout on HttpRequest.Builder. This would then cover all cases - but do we really want to timeout in the case of ofInputStream or ofPublisher if the caller doesn't read the body fast enough?
I have implemented a PerformHttpPostRequest function which is supposed to send a post request contains a JSON type body and get a JSON response via Apache HttpClient.
public static String PerformHttpPostRequest(String url, String requestBody) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(requestBody);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
return (new BufferedReader(new InputStreamReader(is, "UTF-8"))).readLine();
}
The problem is, the code works perfect on developing environment, but when running the war file with a tomcat server but the request is not executed.
I've tried adding several catch blocks such as IOException, Exception and the code doesn't get there.
I've added debug prints which demonstrated that the code stops responding at the client.execute(...) command.
The function is called inside a try block, and after executing the .execute(...) command the code does get to the finally block.
I've already searched for a similar problem and didn't find an answer.
Is it a known issue? Does anyone have any idea of what can cause that? Or how can I fix it?
Hi Talor nice to meet you,
Please try to use HttpURLConnection to solve this issue like so:
Java - sending HTTP parameters via POST method easily
Have a nice day.
el profesor
I have tried with RestTemplate.
RequestObject requestObject = new RequestObject();
requestObject.setKey("abcd");
requestObject.setEndpoint(serviceEndPoint);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<RequestObject> requestBody = new HttpEntity<RequestObject>(
requestObject);
ResponseEntity<RequestObject> result = restTemplate.postForEntity(
serviceEndPoint, requestBody, RequestObject.class);
Its very simple and hassle free, hope it helps
Few things you can try out.
- Try to do ping/curl from that box where you are running tomcat.
- Try to have a test method which make a get request to a server which is always reachable. For ex google.com and print the status. That way you could be able to know that you code is actually working or not in server env.
Hope this helps. :)
If the code doesn't pass beyond client.execute(...) but it does execute the finally block in the calling code, then you can find out what caused the aborted execution by adding this catch block to the try block that contains the finally:
catch(Throwable x) {
x.printStackTrace();
}
Throwable is the superclass for all exception and error classes, so catching a Throwable will catch everything.
I create a simple SWT app with a single button. When the button is clicked, the following code gets executed but it just hangs. I know the URL is ok! Any idea of what could be causing this?
HttpGet httpGetRequest = new HttpGet(URL_UUID);
// Execute HTTP request
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
System.out.println("----------------------------------------");
System.out.println(httpResponse.getStatusLine());
System.out.println("----------------------------------------");
Try set timeouts. Otherwise you can use http-request built on apache http api.
Example
static HttpRequest<?> httpRequest = HttpRequestBuilder.createGet(URL_UUID).build();
ResponseHandler<?> responseHandler = httpRequest.execute();
System.out.println(responseHandler.getStatusCode);
I have a link of a servlet as follow :
http://localhost:8080/UI/FacebookAuth?code=1
and I wrote a little program to connect this link, if you manually type this link in browser it types something in a console but as soon as I run my code nothing happens, it seems that the link is not executed
System.out.println("Starting...");
URI url = new URI("http://localhost:8080/UI/FacebookAuth?code=1");
HttpGet hg = new HttpGet();
hg.setURI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(hg);
System.out.println("Finished...");
Can anyone tell me what the problem?
Your code snippet does nothing with the response. All you do is print out, "Finished..." Because you threw away the response, you have no way of knowing what happened. Assuming that you're using the Apache HTTP client, you should add something like this:
System.out.println("Status code: " + response.getStatusLine().getStatusCode());
See http://hc.apache.org/httpcomponents-core-4.2.x/httpcore/apidocs/org/apache/http/HttpResponse.html for the methods you can execute on the response.
I have this static function which basicly makes a connection to a webpage, send post data along with it and return the received response (JSON object)
The problem that I am having is that no matter what timeout i set, it very often gives a timeout when it is only trying 1 second, with the timeout being 6 seconds that should not happen.
public static String makeRequest(String path, String info) throws Exception
{
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 6000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 6000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httpost = new HttpPost(path);
StringEntity jsonobj = new StringEntity(info);
httpost.setEntity(jsonobj);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpost, responseHandler);
return response;
Now I have seen some issues like this but I could not find an answer that could help me.
Some say it is due to the fact that it is not threadsafe, however, I do not do multiple calls at the same time, it is all done in order. The issue evens occurs on the first try, which should not happen because of this reason as there are no multiple connection/httpposts yet, let alone from different threads.
However it does happen a lot lately, sometimes it did not occur for a few days or barely in those days.
I tried looking at the AndroidHttpClient, but it does not seem to support HttpPost, so that is not usefull either (or I am wrong with this?)
The data for both path and info is correct, tested it. Also my server does not have issues.
Some say it can be your network, but I have it on 3 wifi networks tested today. Strangly, on the internet connection of my mobile provider it does not or barely occur.
I have read in one answer that it may be because of the ISP changing header information. I have tried using different values for the user-agent but that also did not work.
I hope someone can be of help and for that i would be grateful as it really frustrates me that this keeps happening.
If TCP detects a connection reject (i.e. an incoming RST) before the timeout period, it is a failure. There is no point in waiting out the timeout in this case, and it is to be expected that a retry will only fail again the same way. The timeout is for the case when there is no response.