I have a URL of an API which is working fine if run in advanced rest client of chrome directly. I want this URL to trigger from my own REST API code which should run it in advanced rest client and stores the result in variable. How can I do this?
Asked
Active
Viewed 1,861 times
-1
-
why do you need it to run in advanced rest client? – Romski May 14 '15 at 05:42
2 Answers
0
Use Apache HttpClient library https://hc.apache.org/ or some other third party open source libraries for easy coding. If you are using apache httpClient lib, please google for sample code. Tiny example is here.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet('http://site/MyrestUrl');
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = '';
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
return (rd);
If there are any restriction to use third party jars, you can do in plain java too.
HttpURLConnection conn = null;
try {
URL url = new URL("http://site/MyRestURL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", ""); // add your content mime type
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

bobs_007
- 178
- 1
- 10
-
thanks for the answer. it helped me with the url with http. but it did not work with https. i tried to look for similer structure for https, but could not find any. can you please help me with some link or such structure which takes the https url. thanks. – Shashank shekhar Dubey May 19 '15 at 07:02
-
Please review question and answers. It helps you, if you want certificate solution. http://stackoverflow.com/questions/1757295/using-https-with-rest-in-java – bobs_007 May 20 '15 at 00:20
-
This is well explained blog. http://javaskeleton.blogspot.de/2010/07/avoiding-peer-not-authenticated-with.html – bobs_007 May 20 '15 at 00:27
0
In plain java, try like this. My advice please try to use good open source rest/http clients. There are many example in net.
String httpsUrl = "https://www.google.com/";
URL url;
try {
url = new URL(httpsUrl);
HttpsURLConnection con = HttpsURLConnection)url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

bobs_007
- 178
- 1
- 10