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"

<?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>
    <getCountryCityByIp xmlns="http://WebXml.com.cn/">
      <theIpAddress>string</theIpAddress>
    </getCountryCityByIp>
  </soap:Body>
</soap:Envelope>

 */

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");
       
            //这样就有了下面的格式
        // <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/">

        
        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);
//  这样就有了下面的格式
//      <soap:Body>
//        <getCountryCityByIp xmlns="http://WebXml.com.cn/">
//        <theIpAddress>{ip}</theIpAddress>
//      </getCountryCityByIp>
//    </soap:Body>
        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 = "<?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>" + "<getCountryCityByIp xmlns=\"http://WebXml.com.cn/\">"
                + "<theIpAddress xsi:type=\"xsd:string\">" + ip + "</theIpAddress>" + "</getCountryCityByIp>"
                + "</soap:Body>" + "</soap:Envelope>";
        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);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,602评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,442评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,878评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,306评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,330评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,071评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,382评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,006评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,512评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,965评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,094评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,732评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,283评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,286评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,512评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,536评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,828评论 2 345

推荐阅读更多精彩内容