Mithun Debnath
Mithun Debnath

Reputation: 588

how to call an external api from spring mvc controller

hello my controller is

@Controller
public class HomeController{ 
@RequestMapping(value = "/inString={name}", method = RequestMethod.GET)

      public @ResponseBody String getGreeting(@PathVariable String name, String result) {

      //below is the url has given.I want to pass the name string to the below url for the input_text parameter
      //http://ipaddress/input?input_text=tell me something&target_val=hi;

       result=the_result_provided_from_the_above_URL ; 
        return result;
}
}

I am able to get the pathVariable name.Now I want to pass the name to another URL which returns a string and that string will be returned from the controller.I tried but have not been able to call an URL from the controller.

Upvotes: 0

Views: 4289

Answers (1)

Fran Montero
Fran Montero

Reputation: 1680

You can call a servlet using Apache's HttpClient. This is an example:

...
private static final String SERVLETURL = "http://ipaddress/input?input_text=tell";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(SERVLETURL);
CloseableHttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
String responseBody = getStringFromInputStream(response.getEntity().getContent());
//Processing here
EntityUtils.consume(entity);
...

Upvotes: 1

Related Questions