2

i am really new to the REST world, or in fact the WebApp side of java, so please don't mind if it's a silly question. I have a web page where pressing a button will call the following JS function:

function testFunction(){
        $(document).ready(function() {
            $.ajax({
                url: "http://localhost:8080/test/webapi/myresource",
                type: 'get',
                success: function (data) {
                    console.log(data)
                }
                });
        });
    }

where the above url is handled by my OWN web service(which is in java), that is the above GET will call the following Web Service:

@Path("myresource")
public class MyResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
    return "Got it!";
}}

All i wanna do here is instead of returning "Got It", i wanna call another javascript function(dedicated to handle server kind of request) involving EXTERNAL rest call such as this:

        function externalResource() {
        $(document).ready(function() {
            $.ajax({
                url: "any_external_rest_call",
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    document.getElementById('demo').innerHTML = "Perfect"
                }
                });
        });
    }

where i wanna return the data from the externalResource function to getIt() to finally the testFuntion(), i know its possible, but couldn't find much of the details online. It would be really helpful if someone could clear this up to me.

SpaceyBot
  • 304
  • 3
  • 12
  • 1
    I don't understand, you want to call an "another javascipt function" from inside a Java function call? – zero298 Jul 16 '18 at 15:02
  • 1
    why don't you create a webclient in JAVA function `getIt()` and use full URL of `"any_external_rest_call"`to call the external webservice and return the results as results of `getIt()` method – rt2800 Jul 16 '18 at 15:04
  • 1
    It sounds like you want your API to grab data from another API, then process it and forward it to the client. Which means all you need is to make an API call from Java (going through the client for this is nonsense). Which means you need this: https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – Chris G Jul 16 '18 at 15:06
  • You could use nested fetch, the code is easier to read than ajax calls : https://medium.com/@wisecobbler/using-the-javascript-fetch-api-f92c756340f0 and allow you to nest many queries one after another – Ayrton Dumas Jul 16 '18 at 15:14

3 Answers3

1

You cannot call JavaScript code from your REST method in Java. However, you can use the ClientBuilder of the javax.ws.rs.client package.

Your method could look like this:

@Path("myresource")
public class MyResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {

        client = ClientBuilder.newClient();
        target = client.target("http://api.anotherRestService.com/details/")

        return target.request(MediaType.APPLICATION_JSON)
            .get();
    }
}

This is just an example, I didn't try it in a real environment, but this is how you can do it. Now, you can call with your JS method testFunction the REST method of your Java backend. In you REST method getIt you call another rest service with the created client. The result of the second rest call is returned to your JS method testFunction.

kedenk
  • 609
  • 5
  • 9
  • thanks a lot, but when i return it, the callback success function in testFunction is not getting executed, it says in console "net::ERR_INCOMPLETE_CHUNKED_ENCODING", i even tried to change the produces param with MediaType.APPLICATION_JSON, still no luck – SpaceyBot Jul 17 '18 at 06:28
  • Did you also define application/json in the original request (ajax)? There could also be a mismatch. Ajax has the two fields `contentType` and `datatype` which should be defined, too. What contentType provides the second rest call? What data do you request for the second service? A large amount of data could cause a timeout problem. – kedenk Jul 17 '18 at 09:25
  • actually i changed the final return into an entity of a string and returned it, it then worked.. thanks a lot dude – SpaceyBot Jul 17 '18 at 13:06
0

Take a look at his: RestTemplate. This is Spring, however. Seeing as you are using JAX-RS maybe take a look at this: Jersey.

The flow you describe is not possible, it is however possible to chain several requests while using data from the response of the previous response:

$(document).ready(function() {
    $.ajax({
        url: "http://localhost:8080/test/webapi/myresource1",
        type: 'get',
        success: function (data) {
            $.ajax({
                url: "http://localhost:8080/test/webapi/myresource2?id="+data.id,
                type: 'get',
                success: function (data) {
                    console.log(data)
                }
            });
        }
    });
});
SBylemans
  • 1,626
  • 12
  • 26
0

If you wish to call another URL from your server, its a redirect call. Following would be an example server side code if you are using Spring framework.

@RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
    RedirectView redirectView = new RedirectView();
    redirectView.setUrl("http://www.google.com");
    return redirectView;
}

As others have mentioned, you can also use Spring RestTemplate to do this.

priteshbaviskar
  • 1,718
  • 1
  • 17
  • 24