HttpClient parameters not being added to the executing method - java

Sorry that it's potentially an easy answer but I can't find anything.
I currently have the method:
public MediaSource getConvertedMediaServletCall(String format) throws HttpException, IOException{
HttpClient httpclient = new HttpClient();
GetMethod httpGet = new GetMethod(MEDIA_SERVER_URL);
httpGet.getParams().setParameter("format", format);
httpGet.getParams().setParameter("handler", "handle");
try{
int statusCode = httpclient.executeMethod(httpGet);
byte[] responseBody = httpGet.getResponseBody();
Now I know this doing really do anything, this has to be worked on once I get the problem working. The problem is, I am create what I believe a http client, which executes the get method. Now the problem is when the code runs the httpClient.executeMethod(httpGet); the servlet doGet method is being executed, and I know this for a fact, but the parameters are never passed through from this executing method.
Anyhelpwould be appreciated..

For anyone still wondering, although HttpClient gives you the methods for adding parameters, it won't work. Get parameters have to passed in the URL, and these parameters are being added to the body of the message, like a post request.
The workaround to this is discussed here: How do I add query parameters to a GetMethod (using Java commons-httpclient)?

Related

HTTP post request doesn't respond on production environment (war with tomcat server)

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.

Does using a try-with-resource block for CloseableHttpClient also close the returning CloseableHttpResponse?

I'm trying to workout if a try-with-resource closes just the CloseableHttpClient, or also closes the response too.
For example,
private static CloseableHttpResponse sendRequest()
throws IOException
{
final HttpUriRequest httpUriRequest =
buildRequest(url, requestMethod, requestParameters, httpHeaders);
try (CloseableHttpClient client = HttpClientBuilder.create().build())
{
return client.execute(httpUriRequest);
}
}
We all know this will close the CloseableHttpClient as expected. What about the result of that call though? CloseableHttpClient returns a CloseableHttpResponse. Does that also need to be closed, either in the invoking code, or somewhere else? Or is it closed at the same time as CloseableHttpClient with that try-with-resource?
Bonus question: How can I prove to myself that things are actually being closed? I'm looking at the thread pool in IntelliJ but can't quite workout where/when things are closing.
The answer given by Jhilton is perfectly correct (my +1). However, as far as HttpClient specific resource management is concerned closure of HttpClient instance results in closure of all kept alive and active connection, including those currently associated with HttpResponse instances. That essentially means one does not have to close HttpResponse instances if closing HttpClient instance used to execute the message exchange but such pattern is very much discouraged.
try-with-resource will close only the resources declared in the try clause
try (CloseableHttpClient client = HttpClientBuilder.create().build())
e.g It will only close the variable "client"
Also if the response were to be closed, It would become a problem to extract the data, so the responsibility of closing it should fall elsewhere.

Parameters for request HttpGet aren't set

I try to set parameters for request Get by
HttpGet.setParams method (new BasicHttpParams () .setParameter ("oauth_token", "Valid_token"))
to receive a request similar brought below:
https://api.soundcloud.com/me?oauth_token=Valid_token
But when sending request by HttpClient.execute (request) method;
In logs shows that the oauth_token parameter wasn't added to request, prompt, in what a problem. When I inscribe the correct line in the browser everything works, in this case parameter simply isn't added to request
I found a solution, it was necessary to set parameters not through the setParams method (), and obviously to set them in URI, how here https://api.soundcloud.com/me? me? oauth_token=A_VALID_TOKEN

how to connect to url from java

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.

difference of HttpClient singleton instance or not

As HttpClient document suggests - Generally it is recommended to have a single instance of HttpClient per communication component or even per application.
I got different behaviours between HttpClient is singleton or not.
1) With singleton, I first created a global static HttpClient instance, and send every request with this instance with below segment,
PostMethod post = new PostMethod(url);
int status = httpClient.executeMethod(post);
2) Without singleton, I send every request by creating a new HttpClient instance
PostMethod post = new PostMethod(url);
HttpClient httpClient = new HttpClient();
int status = httpClient.executeMethod(post);
The differences are, without singleton, everything is OK, I can get the correct result separately in consecutive requests. But with singleton, it seems there is some request context, the second request doesn't return the response string as expected because of the first request parameter (weird!!).
I don't have the service codes and server configuration. Can you help me figure out the possible reason?
Thanks in advance.

Categories

Resources