-1

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?

1
  • why do you need it to run in advanced rest client? Commented May 14, 2015 at 5:42

2 Answers 2

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

  } 
Sign up to request clarification or add additional context in comments.

3 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.