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?
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();
}