Java调用webservice

本文详细介绍了如何使用Java调用WebService接口,包括获取请求路径、通过WSDL文件生成访问接口、使用Axis2工具包以及自定义接口访问的方法。通过具体的天气预报接口示例,讲解了SOAP协议和HTTP请求的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

获取请求路径

 接口调用

获取接口请求方式

通过wsdl文件生成访问接口

axis2的工具包

执行如命令:wsdl2java -url d:demo.wsdl -p client -s -o stub(url可以是本地也可以是网络地址如下图标注)

获取wsdl文件,以上述的天气预报为例点击WSDL获得内容如下

自定义接口访问

SOAP协议访问

HTTP请求


获取请求路径

一般是接口提供人提供,提供wsdl文件或者其他请求方式

可以根据wsdl文件通过axi生成Java文件,可以像调用本地服务一样调用webservice接口

20多个常用的免费WebService接口 https://www.cnblogs.com/jpfss/p/8397596.html,取第一个天气预报为例

 接口调用

获取接口请求方式

可参考:https://blog.youkuaiyun.com/qq_31183297/article/details/79522746

通过wsdl文件生成访问接口

生成方式为如下:

axis2的工具包

执行如命令:wsdl2java -url d:demo.wsdl -p client -s -o stub(url可以是本地也可以是网络地址如下图标注)

下图是我根据天气预报生成的文件,由于我没配置axis2的环境变量,所以进入cmd要在axis2的bin目录下执行该命令,生成的文件就在stub下,包名就是client,然后将文件放到项目中就可以用了

当然需要引入如下依赖

<!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/wsdl4j/wsdl4j -->
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
            <version>1.6.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/axis/axis-jaxrpc -->
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis-jaxrpc</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery -->
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.axis2/axis2-transport-http -->
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-transport-http</artifactId>
            <version>1.7.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.axis2/axis2-adb -->
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-adb</artifactId>
            <version>1.7.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.axis2/axis2-transport-local -->
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-transport-local</artifactId>
            <version>1.7.9</version>
        </dependency>
      

获取wsdl文件,以上述的天气预报为例点击WSDL获得内容如下

自定义接口访问

打开如上的天气预报服务界面,点击Endpoint,则看到提供了几种访问形式

SOAP协议和HTTP协议访问

SOAP协议访问

请求参数

POST /WebServices/WeatherWebService.asmx HTTP/1.1
Host: www.webxml.com.cn
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getSupportCity"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getSupportCity xmlns="http://WebXml.com.cn/">
      <byProvinceName>string</byProvinceName>
    </getSupportCity>
  </soap:Body>
</soap:Envelope>

Java代码​​​​​​​

package com.cjb.util.webservice;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;

public class SoapRequestUtil {

    public static void main(String[] args) throws Exception {
        String wsdl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
        int timeout = 10000;
        StringBuffer sb = new StringBuffer("");
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "  <soap:Body>\n" +
                "    <getSupportDataSet xmlns=\"http://WebXml.com.cn/\" />\n" +
                "  </soap:Body>\n" +
                "</soap:Envelope>");

        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(wsdl);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);// 设置连接超时
        client.getHttpConnectionManager().getParams().setSoTimeout(timeout);// 设置读取时间超时
        RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");// 然后把Soap请求数据添加到PostMethod中
        postMethod.setRequestHeader("SOAPAction","http://WebXml.com.cn/getSupportDataSet");//设置请求头部,否则可能会报 “no SOAPAction header” 的错误
        postMethod.setRequestEntity(requestEntity);// 设置请求体
        int status = client.executeMethod(postMethod);
        InputStream is = postMethod.getResponseBodyAsStream();// 获取响应体输入流
        String result = IOUtils.toString(is);// 获取请求结果字符串
        URL url = new URL(wsdl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(sb.toString().getBytes("utf-8"));
        dos.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line = null;
        StringBuffer strBuf = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            strBuf.append(line);
        }
        dos.close();
        reader.close();
        System.out.println(strBuf.toString());
    }

}

HTTP请求

分为get和post两种方式

代码如下:

package com.cjb.util.webservice;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

    public static void doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        OutputStreamWriter out = null;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
//            //2.传入参数部分
//            connection.setDoOutput(true);
//            // 得到请求的输出流对象
//            out = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//            // 把数据写入请求的Body
//            out.write("byProvinceName=陕西"); //参数形式跟在地址栏的一样
//            out.flush();
//            out.close();
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    System.out.println(temp);
                }
            }
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            if(null != out){
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
            connection.disconnect();// 关闭远程连接
        }
    }

    public static void doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        OutputStreamWriter out = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //2.传入参数部分
            // 得到请求的输出流对象
            out = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            out.write("byProvinceName=陕西"); //参数形式跟在地址栏的一样
            out.flush();
            out.close();

            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    System.out.println(temp);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 断开与远程地址url的连接
        }
    }

    public static void main(String[] args) {
        doPost("http://www.webxml.com.cn//WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=陕西",null);
        doGet("http://www.webxml.com.cn//WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=陕西");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值