Http方式调用WebService

以手机号码归属地为例:http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL

1. 在 src 下新建调用参数模板 mobileCodeWS.template
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://WebXml.com.cn/">
   <soap:Header/>
   <soap:Body>
      <web:getMobileCodeInfo>
         <!--Optional:-->
         <web:mobileCode>{mobileCode}</web:mobileCode>
         <!--Optional:-->
         <web:userID>{userID}</web:userID>
      </web:getMobileCodeInfo>
   </soap:Body>
</soap:Envelope>
此模板内容可以通过 SoapUI 工具获得,或者从 http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getDatabaseInfo 找到。

2. 编写工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
 
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
 
import com.sun.org.apache.xml.internal.security.utils.Base64;
 
/**
 * WebService调用工具类
 */
public class HttpConnectUtils {
    
    /**
     * 基于SOAP1.1协议的调用
     * @param address 接口地址
     * @param template 参数模板
     * @param params 参数,可以为空
     * @return 调用结果
     * @throws Exception 调用失败抛出此异常
     */
    public static String submitBySoap11(String address, String template, Map<String, String> params) throws Exception {
        return submit(address, template, params, null, null, SOAPConstants.SOAP_1_1_PROTOCOL);
    }
 
    
    /**
     * 基于SOAP1.2协议的调用
     * @param address 接口地址
     * @param template 参数模板
     * @param params 参数,可以为空
     * @return 调用结果
     * @throws Exception 调用失败抛出此异常
     */
    public static String submitBySoap12(String address, String template, Map<String, String> params) throws Exception {
        return submit(address, template, params, null, null, SOAPConstants.SOAP_1_2_PROTOCOL);
    }
 
    /**
     * 基于SOAP1.1协议的调用
     * @param address 接口地址
     * @param template 参数模板
     * @param params 参数,可以为空
     * @param username 用户名
     * @param password 密码
     * @return 调用结果
     * @throws Exception 调用失败抛出此异常
     */
    public static String submitBySoap11(String address, String template, Map<String, String> params, String username, String password) throws Exception {
        return submit(address, template, params, username, password, SOAPConstants.SOAP_1_1_PROTOCOL);
    }
 
    /**
     * 基于SOAP1.2协议的调用
     * @param address 接口地址
     * @param template 参数模板
     * @param params 参数,可以为空
     * @param username 用户名
     * @param password 密码
     * @return 调用结果
     * @throws Exception 调用失败抛出此异常
     */
    public static String submitBySoap12(String address, String template, Map<String, String> params, String username, String password) throws Exception {
        return submit(address, template, params, username, password, SOAPConstants.SOAP_1_2_PROTOCOL);
    }
    
    private static String submit(String address, String template, Map<String, String> params, String username, String password, String protocol) throws Exception {
        
        HttpURLConnection conn = null;
        String result = null;
        try {
            // 载入请求参数模板
            String requestBody = read(ClassLoader.getSystemResource(template).openStream());
            // 替换参数
            if(params != null) {
                for(Map.Entry<String, String> entry : params.entrySet()) {
                    requestBody = requestBody.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
                }
            }
            
            URL url = new URL(address);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST"); // 请求方式
            conn.setDoOutput(true); // 向服务器发送数据
            conn.setDoInput(true); // 获取服务端的响应
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            conn.setReadTimeout(5000); // 读取超时
            conn.setConnectTimeout(5000); // 服务器响应超时
            conn.setUseCaches(false); // 不使用缓存
            
            if(username != null && password != null) {
                String author = "Basic " + Base64.encode((username + ":" + password).getBytes());  
                conn.setRequestProperty("Authorization", author);   
            } 
            
            conn.getOutputStream().write(requestBody.getBytes("UTF-8"));
            if(conn.getResponseCode() == 200) {
                result = parseXml(conn.getInputStream(), protocol);
            } else {
                throw new RuntimeException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }
    
    private static String read(InputStream in) {
        StringBuilder builder = new StringBuilder();
        String str = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            while((str = reader.readLine()) != null) {
                builder.append(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return builder.toString();
    }
    
    private static String parseXml(InputStream in, String protocol) {
        String content = null;
        try {
            content = MessageFactory.newInstance(protocol)
                    .createMessage(new MimeHeaders(), in)
                    .getSOAPBody()
                    .getTextContent();
        } catch (SOAPException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return content;
    }
}
3. 测试
import java.util.HashMap;
import java.util.Map;
 
public class Test {
 
    public static void main(String[] args) {
        
        String template = "mobileCodeWS.template";
        String address = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";
        Map<String, String> params = new HashMap<>();
        params.put("mobileCode", "1830061");
        params.put("userID", "");
        
        try {
            String result = HttpConnectUtils.submitBySoap12(address, template, params);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
4. 运行结果
1830061:河南 焦作 河南移动全球通卡
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值