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?
2 Answers
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();
}
3 Comments
Shashank shekhar Dubey
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.
bobs_007
Please review question and answers. It helps you, if you want certificate solution. stackoverflow.com/questions/1757295/…
bobs_007
This is well explained blog. javaskeleton.blogspot.de/2010/07/…
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();
}