how to connect to url from java - 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.

Related

Jenkins giving 403 in EC2 Server after passing the crumb in the request headers

i am using the CSRF Jenkins crumbs in the API call to create a new job in Jenkins from Java.
I tried the following
Called the API to get the crumb data
http://admin:11542c80972c3a2b863453d234de68b1d#10.139.163.33/crumbIssuer/api/json
I also tried with the below URL
http://10.139.163.33/crumbIssuer/api/json
The below is the JSON response obtained from the server
{"_class":"hudson.security.csrf.DefaultCrumbIssuer","crumb":"b272a09b604e7b7cc8ee1431f0a0143fa1422db2fb5f92955b0356a31da37463","crumbRequestField":"Jenkins-Crumb"}
In the next step, I am making a call to the Jenkins to create a new job with the header as
Jenkins-Crumb:b272a09b604e7b7cc8ee1431f0a0143fa1422db2fb5f92955b0356a31da37463
Jenkins is giving me 403, I am using HttpGet to get the token and using HttpPost with the header as above and sending to jenkins.
When i try with postman, it is not giving this error. I am running the Java application in 1 ec2 server and jenkins on another ec2 server.
There are no proxies, I also tried to use the various options like the enable proxy compatibilty, restarting jenkins etc, but not working.
Please give any pointers.
Java code used is
HttpPost postRequest = new HttpPost(url);
JenkinsCrumb crumb = jenkinsHelper.getCrumb();
String encodedPassword = Base64.getEncoder().encodeToString((user + ":" + pwd).getBytes());
postRequest.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedPassword);
postRequest.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb()));
return postRequest;
The code to get the crumb is
String urlWithToken = "http://" + (user + ":" + pwd) + "#";
HttpGet request = new HttpGet(jenkinsBaseUrl.replace("http://", urlWithToken) + "crumbIssuer/api/json");
request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedPassword);
CloseableHttpResponse httpResponse = httpClient.execute(request);
I have also tried with the CURL command and still getting the same response
I was able to fix this issue by using the same HttpClient (CloseableHttpClient) for both the CRUMB and the POST Request. Earlier, I was using 2 separate clients one for getting the crumb and new one for the posting of the data. Using a shared httpclient for both of these resulted in success state.
Hope this helps any other developer facing similar issue.

Getting Target host is not specified

I am calling prometheus server via Grafana I am able to make below request using postman but when I am trying same uri with java code getting below exception
Caused by: org.apache.http.ProtocolException: Target host is not specified
at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
... 31 common frames omitted
My piece of code is as given below.
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String PM_UI_SERVER_URI = "http://" + PM_SERVER_HOST + ":" + getPMUiServerPort();
String uriStr= PM_UI_SERVER_URI + PM_SERVER_BASE_URI + queryString +"&start="+String.valueOf(startTime)+"&end="+String.valueOf(endTime)+"&step=150";
//logger.info("Execute Query uri string: "+uriStr);
String str="http://10.61.244.58:31000/api/datasources/proxy/1/api/v1/query_range?query=em_core_used_heap_mem_mb{job=\"eric-em-om-server\"}&start=1592981880&end=1592982180&step=15";
String encodedurl = URLEncoder.encode(str,"UTF-8");
//URI uri = new URI(encodedurl);
//HttpGet httpget = new HttpGet("http://10.61.244.58:31000/api/datasources/1");
HttpGet httpget = new HttpGet(encodedurl);
httpget.addHeader("Authorization", token);
httpget.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = httpClient.execute(httpget);
Can someone please help as I am stucked here.
Try to build up the URL piece by piece rather than going straight for the completed URL. You can do this in a debug session using the expression builder in intelliJ IDE.
set breakpoint at the line ... = httpClient.execute(httpget); and exercise this code from a test/running the application in debug mode.
highlight httpClient.execute(httpget)
either right click this selection and click "Expression builder" OR use Alt+F8
now try to perform the execute the GET (HttpGet) request for http://10.61.244.58:31000/
ensure you're getting a 200 response status or equivalent.
next you should be able to add the next bit like http://10.61.244.58:31000/api/datasources/proxy/1/api/v1/query_range (Note I'd also try without the proxy as the URL may be problematic because your requests are being proxied according to the docs here: https://grafana.com/docs/grafana/latest/http_api/data_source/#data-source-proxy-calls
I'd try then adding the query params individually and combined. This isn't going to necessarily resolve your problem... but if you can at the same time tail any logs on the grafana server/proxy server you may get some more detailed information that will help lead your investigation.

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.

Read file of content-disposition with java

I am developing a web-app that needs to query an ontology through a REST-API.
If I call the API through the browser, it opens a pop-up "Save As" through which I can save the file.
This is because the header of the response contains:
Content-Disposition: attachment; filename = query-result.srx
The problem is that I would like to receive the file within my web-app without using the browser.
The web-app is write on java and I use Apache HttpClient for send and receive, HTTP request and response:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
If I try to get the entity's content:
httpResponse.getEntity().getContent()
It return a useless value.
It 's something that you can do with this library, or should I use another library.
I found another question similar to mine but no one answered.
java-javascript-read-content-disposition-file-content
Thanks to all who answer me!
I realized that the error was in the query that I used the REST API. So the operations I did in Java were correct. With the command
httpResponse.getEntity().getContent()
you can take the content that is returned even if this file is described in the content-disposition.
Thanks to #Julian Reschke

Using HttpClient to send JSON query string in a URL to a web service (Java)

I have a web service that I built... what I am trying to do now is send a simple request that contains a json query string from a Tapestry web app to that web service. I searched around and most people say to use Apache HttpClient to achieve this. Along with HttpClient I am using URIBuilder.
The Json object that I am trying to send looks like this
{"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
*I realize the issues with the password being sent in plain text etc...
The url that works (tested by manually entering in a web browser and this web service already services an Android client and an iOS client) looks like this
http:// ##.##.###.##/createuser?json={"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203-555-5555"},"password":"dead"}
Here is the HttpClient code that I have mashed together from google'ing around trying to figure out why this wont work. Essentially what I am trying to do is create a URI with URIBuilder and then construct an HttpPost or HttpGet object with the newly built URI. But something is going wrong in the URIBuilding process. When I debug, an exception gets thrown when I try to set all the aspects of the URI.
Object onSuccess() throws ClientProtocolException, IOException, URISyntaxException{
// json = {"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
String json = user.toJson();
URIBuilder builder = new URIBuilder();
// Error gets thrown when I step over the next line
builder.setScheme("http").setHost("##.###.##.###").setPort(8080).setPath("createuser").setQuery("json=" +json);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
DefaultHttpClient httpClient = new DefaultHttpClient();
String tmp = request.getURI().toString();
HttpResponse response = httpClient.execute(request);
index.setResponse(EntityUtils.toString(response.getEntity()));
return index;
The error that comes back when I step over the line that I commented in the code is
[ERROR] TapestryModule.RequestExceptionHandler Processing of request failed with uncaught exception:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;
java.lang.NoSuchMethodError:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;
I have tried a lot of other combinations of methods and objects to get this request to send off to the server correctly and nothing seems to work. Hopefully I am overlooking something relatively simple.
Thanks in advance for any guidance you can provide.
You most likely have the wrong version or two versions of the apache httpcomponents on your classpath. If you are running Tapestry it will print out all packages on the classpath on the error page. Investigate there, find which httpcomponents is loaded, figure out where it comes from and fix it.
If this does not work, you should share some of your runtime environment with us. Which servlet engine, running from which IDE or are you running from the command line. Are you using Maven? If so share your pom. Etc.

Categories

Resources