如何调用Web服务

时间:2022-05-22 12:20:54

I have a php file in my server that echo "hello world". (link >> http://localhost/myservic/service.php )

我的服务器中有一个回复“hello world”的php文件。 (链接>> http://localhost/myservic/service.php)

What I want to do now is calling this service from my JSP page and send the output (hello world) to my controller method and then print it using println

我现在要做的是从我的JSP页面调用此服务并将输出(hello world)发送到我的控制器方法然后使用println打印它

How can I do this??

我怎样才能做到这一点??

please answer with example code

请回答示例代码

1 个解决方案

#1


0  

You need to basically create a web service client to consume the service located at the URL that you've mentioned. There are various apis available in Java to do that .. here's one that uses the java.net packages .. below is a sample code for better understanding

您需要基本上创建一个Web服务客户端来使用位于您提到的URL的服务。 Java中有各种各样的api可以做到这一点..这里是一个使用java.net包的..下面是一个示例代码,以便更好地理解

        URL url = new URL("http://localhost:port/path/to/your/service");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/xml");

        if (conn.getResponseCode() != 200) 
        {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        // for reading the output
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String apiOutput = br.readLine();
        System.out.println(apiOutput);
        conn.disconnect();

This example is taken from This post where you can find a much detail explanation.

此示例取自本文,您可以在其中找到更详细的说明。

#1


0  

You need to basically create a web service client to consume the service located at the URL that you've mentioned. There are various apis available in Java to do that .. here's one that uses the java.net packages .. below is a sample code for better understanding

您需要基本上创建一个Web服务客户端来使用位于您提到的URL的服务。 Java中有各种各样的api可以做到这一点..这里是一个使用java.net包的..下面是一个示例代码,以便更好地理解

        URL url = new URL("http://localhost:port/path/to/your/service");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/xml");

        if (conn.getResponseCode() != 200) 
        {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        // for reading the output
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String apiOutput = br.readLine();
        System.out.println(apiOutput);
        conn.disconnect();

This example is taken from This post where you can find a much detail explanation.

此示例取自本文,您可以在其中找到更详细的说明。