Webservice 接口调用

本文介绍了一种简化Webservice接口调用的工具,通过HTTP POST方式发送SOAP请求,避免了使用wsimport产生的代码臃肿问题。文章提供了工具的实现代码,并通过两个示例展示了如何调用检查QQ在线状态及查询IP地址归属的服务。

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

  • 最近项目中频繁遇到web service接口调用,调用起来麻烦,若使用wsimport生成客户端的方式调用,造成项目代码臃肿,简单整理个ws调用工具,便于在项目开发中使用。

  • WebServiceUtil
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * Web service调用工具
 * @author Cheng.Wei
 * @date 2018年8月7日
 * @since jdk1.8
 */
public class WebServiceUtil {
    /**
     * 发送请求
     * @param request
     * @return
     * @throws IOException 
     */
    public static InputStream post(final Request request) throws IOException{
        URL url = new URL(request.getUrl());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();
        if(request.getAccount()!=null){
            String auth = request.getAccount().getUsername() +":"+ request.getAccount().getPassword();
            byte[] authstr = Base64.getEncoder().encode(auth.getBytes());
            connection.setRequestProperty("Authorization", "Basic "+new String(authstr));
        }
        connection.connect();
        String soapXML = request.getBody();
        try(OutputStream os = connection.getOutputStream()){
            os.write(soapXML.getBytes());
            if(connection.getResponseCode()!=200){
                throw new IOException("response:"+connection.getResponseCode());
            }
            InputStream is = connection.getInputStream();
            return is;
        }
    }
}

  • Request 请求报文
/**
 * 请求报文
 * @author Cheng.Wei
 * @date 2018年8月7日
 */
public class Request {
    /**访问地址*/
    private String url;
    /**XML格式数据*/
    private String body;
    /**账号信息*/
    private Account account;


    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        this.url = url;
    }


    public String getBody() {
        return body;
    }


    public void setBody(String body) {
        this.body = body;
    }


    public Account getAccount() {
        return account;
    }


    public void setAccount(Account account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "Request [url=" + url + ", body=" + body + ", account=" + account + "]";
    }

    /**
     * 账号信息
     * @author Cheng.Wei
     * @date 2018年8月7日
     */
    public class Account{
        /**账号*/
        private String username;
        /**密码*/
        private String password;
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }

        @Override
        public String toString() {
            return "Account [username=" + username + ", password=" + password + "]";
        }
    }

}

  • *测试代码
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

/**
 * Web service 测试
 * @author Cheng.Wei
 *
 * @date 2018年8月7日
 */
public class WsTest {
    /**
     * QQ在线
     * @throws IOException
     */
    @Test
    public void qqOnline() throws IOException {
        /**QQ号*/
        String qq = "10086";
        String requestXml =  "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">"
                            + "<soapenv:Header/>"
                            +    "<soapenv:Body>"
                            +        "<web:qqCheckOnline>"
                            +           "<web:qqCode>"+qq+"</web:qqCode>"
                            +        "</web:qqCheckOnline>"
                            +    "</soapenv:Body>"
                            + "</soapenv:Envelope>";
        Request request = new Request();
        request.setBody(requestXml);
        request.setUrl("http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl");
        try(InputStream inputStream = WebServiceUtil.post(request)){
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[1024];
            int len = 0;
            String str = null;
            while((len=inputStream.read(b)) != -1){
                str = new String(b, 0, len, "utf-8");
                sb.append(str);
            }
            System.out.println(sb.toString());
        }
    }
    /**
     * IP归属
     * @throws IOException 
     */
    @Test
    public void ipAddress() throws IOException{
        /**IP*/
        String ipAddress = "8.8.8.8";
        String requestXml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">"
                            + "<soapenv:Header/>"
                            +   "<soapenv:Body>"
                            +       "<web:getCountryCityByIp>"
                            +           " <web:theIpAddress>"+ipAddress+"</web:theIpAddress>"
                            +       "</web:getCountryCityByIp>"
                            +   "</soapenv:Body>"
                            +"</soapenv:Envelope>";
        Request request = new Request();
        request.setBody(requestXml);
        request.setUrl("http://ws.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl");
        try(InputStream inputStream = WebServiceUtil.post(request)){
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[1024];
            int len = 0;
            String str = null;
            while((len=inputStream.read(b)) != -1){
                str = new String(b, 0, len, "utf-8");
                sb.append(str);
            }
            System.out.println(sb.toString());
        }
    }
}

  • 运行结果
    这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值