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);
Related
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 am trying to use HttpClient to make HTTP requests in Java. Whenever a url redirects me, I would like to know the status code of the original request and the final url. If I do not disable redirects, the status code is just the status code of the last successful request:
// google.com = tinyurl.com
HttpUriRequest httpUriRequest = new HttpGet("https://google.com/cqvga");
HttpClient httpClient =
HttpClientBuilder.create()
.build();
HttpResponse response = httpClient.execute(httpUriRequest);
System.out.println(response.getStatusLine().getStatusCode()); // 200
System.out.println(response.getHeaders(HttpHeaders.LOCATION).length); // 0
However, if I disable redirect handling then I get the redirect status:
HttpClient httpClient =
HttpClientBuilder.create()
.disableRedirectHandling()
.build();
System.out.println(response.getStatusLine().getStatusCode()); // 301
System.out.println(response.getHeaders(HttpHeaders.LOCATION).length); // 1
Is there anyway without me writing my own RedirectHandler to know the original status code of my first request, and the final url I landed on?
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.
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 been trying to send a POST request from a servlet and the code that I wrote is this:
HttpPost post = new HttpPost(url.build());
post.setEntity(new UrlEncodedFormEntity(nameValue));
post.setHeader("content-type", "application/json");
HttpClient client = new DefaultHttpClient();
HttpResponse res = client.execute(post);
The URL is "https://accounts.google.com/o/oauth2/token" and I send some parameters with this request.
However, when I run this I get AccessControlException.
The HttpPost method that I use here comes from org.apache.http i.e., commons HttpClient API. I have tried a lot but it doesn't seem to work.
So the question is "Is it possible to send a cross domain request using HttpClient?"