java调用IpAddressSearchWebService示例

首先导入对应的包

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.w3c.dom.Node;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Scanner;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.encoding.XMLType;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

/*
 *
以下是 SOAP 1.1 请求和响应示例。所显示的占位符需替换为实际值。
POST /WebServices/IpAddressSearchWebService.asmx HTTP/1.1
Host: www.webxml.com.cn
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getCountryCityByIp"



  
    
      string
    
  


 */

public class IpAddressSearchWebService {

    private static String host = "www.WebXml.com.cn"; // 主机名
    private static String endPoint = "http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx";
    
    public static void main(String[] args) throws ServiceException, IOException, SOAPException, TransformerException {
        System.out.println("getVersionTime的结果为: ");
        getVersionTime();
        System.out.println("getGeoIPContext的结果为: ");
        getGeoIPContext();
        System.out.println("输入要查询的ip地址: ");
        String ip = new Scanner(System.in).nextLine();
        System.out.println("getCountryCityByIp的结果为: ");
        getCountryCityByIp(ip);
    }

    // 测试getVersionTime;
    public static String getVersionTime() throws ServiceException, MalformedURLException, RemoteException {
        //System.out.println("start getVersionTime...");
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(new java.net.URL(endPoint));
        call.setOperation("getVersionTime");
        call.setUseSOAPAction(true);
        call.setSOAPActionURI("http://WebXml.com.cn/getVersionTime");
        call.setOperationName(new QName(host, "getVersionTime"));
        call.setReturnType(XMLType.XSD_STRING);
        String str = (String) call.invoke(new Object[] {});
        System.out.println(str);
        return str;
    }

    // 测试getGeoIPContext;
    public static String[] getGeoIPContext() throws ServiceException, MalformedURLException, RemoteException {
        //System.out.println("start getGeoIpContext...");
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(new URL(endPoint));
        call.setOperation("getGeoIPContext");
        call.setUseSOAPAction(true);
        call.setSOAPActionURI("http://WebXml.com.cn/getGeoIPContext");
        call.setOperationName(new QName(host, "getGeoIPContext"));
        call.setReturnType(new QName(host, "getGeoIPContext"), String[].class);
        String[] s = (String[]) call.invoke(new Object[] {});
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
        //System.out.println("end getGeoIpContext...");
        return s;
    }

    //测试getCountryCityByIp
    public static String getCountryCityByIp(String ip)
            throws ServiceException, SOAPException, IOException, TransformerException {
        SOAPMessage soapMessage = createSOAPMessage(ip);
        return sendSoapMeaage(soapMessage);                         
    }
    
    private static SOAPMessage createSOAPMessage(String ip) throws SOAPException, IOException
    {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        soapMessage = setSOAPMessageHeader(soapMessage);
        soapMessage = setSOAPMessageBody(soapMessage, ip);
        soapMessage.saveChanges();
//        System.out.println("getCountryCityByIp发送的xml文件为:");
//        soapMessage.writeTo(System.out);  
        return soapMessage;
    }   
    
    private static SOAPMessage setSOAPMessageHeader(SOAPMessage soapMessage) throws SOAPException {
        //在getCountryCityByIp中不需要header,所以需要把此节点删除.
        SOAPHeader header = soapMessage.getSOAPHeader();
        if (header != null) {
                header.detachNode();
        }
        return soapMessage;
    }
    
    private static SOAPMessage setSOAPMessageBody(SOAPMessage soapMessage, String ip) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        
        //默认的Prefix为soap-env 不符合标准格式, 改!
        envelope.setPrefix("soap");
        //默认的一个Attribute 不符合标准格式, 删!
        envelope.removeAttribute("xmlns:SOAP-ENV");
        
        
        envelope.setAttribute("xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/");
        envelope.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        envelope.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
       
            //这样就有了下面的格式
        // 

        
        SOAPBody soapBody = envelope.getBody();
        soapBody.setPrefix("soap");
        SOAPElement getCountryCityByIp = soapBody.addChildElement(new QName("http://WebXml.com.cn/", "getCountryCityByIp"));
        SOAPElement theIpAddress = getCountryCityByIp.addChildElement("theIpAddress");
        theIpAddress.addTextNode(ip);
//  这样就有了下面的格式
//      
//        
//        {ip}
//      
//    
        return soapMessage;
    }
    
    
    private static String sendSoapMeaage(SOAPMessage soapMessage) throws SOAPException, MalformedURLException, TransformerException {
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory  
                .newInstance();  
        SOAPConnection connection = soapConnFactory.createConnection();  
        URL url = new URL(endPoint);
        //MimeHeader 在http头部加入SOAPAction
        soapMessage.getMimeHeaders().setHeader("SOAPAction","http://WebXml.com.cn/getCountryCityByIp");
        SOAPMessage reply = connection.call(soapMessage, url);
        //查看接收的xml文件
//      TransformerFactory transformerFactory = TransformerFactory  
//                .newInstance();  
//        Transformer transformer = transformerFactory.newTransformer();        
//        System.out.println("\ngetCountryCityByIp接收的xml文件为:");
//        transformer.transform(reply.getSOAPPart().getContent(), new StreamResult(System.out));  
        connection.close();  
        SOAPBody soapBody = reply.getSOAPBody();  
        Node node = soapBody.getFirstChild(); 
        String result = node.getTextContent();
        System.out.println("\n" + result);
        return result;
    }

    public static void getCountryCityByIpThroughPost(String ip) throws IOException {
        System.out.println("start getCountryCityByIpThroughPost...\n");
        URL url = new URL(endPoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Content-Type", "text/xml");
        conn.addRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "utf8");
        String str = ""
                + ""
                + "" + ""
                + "" + ip + "" + ""
                + "" + "";
        writer.write(str);
        writer.flush();
        writer.close();
        printHtmlSourceCode(conn.getInputStream());
        System.out.println("\nend getCountryCityByIpThroughPost...\n");
    }

    private static void printHtmlSourceCode(InputStream in) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(in, "utf8"));
        String line;
        while ((line = r.readLine()) != null) {
            System.out.println(line);
        }
    }
}

你可能感兴趣的:(java调用IpAddressSearchWebService示例)