---
title: "HttpURLConnection调用WebService"
author: "showcup"
date: "2010-09-03T14:00:26Z"
tags: []
categories: ["编程语言"]
slug: "httpurlconnection-webservice"
draft: false
lastmod: "2010-09-03T14:00:26Z"
id: 754476
url: "https://showcup.iteye.com/blog/754476"
---

protected ResponseMessage httpProtocol\_http(String businessServiceName,RequestMessage message) throws Exception {

        String url\_str = protocol + ":" + "//" + host + ":" + port + uri;

        logger.debug("asip服务地址:" + url\_str);

        URL url = new URL(url\_str);

        URLConnection connection = url.openConnection();

        /\**

         * 构建soap消息

         \*/

        StringBuffer soapMessage = new StringBuffer();

        soapMessage.append("&lt;soap:Envelope xmlns:soap=\\"" + SOAP\_NS + "\\"  soap:encodingStyle=\\"" + ENCODINGSTYLE\_NS

                + "\\" xmlns:xsd=\\"" + XSD\_NS + "\\" xmlns:xsi=\\"" + XSI\_NS + "\\"&gt;");

        soapMessage.append("&lt;soap:Body&gt;");

        soapMessage.append("&lt;ns1:call xmlns:ns1=\\"http://service.asip.regaltec.com/\\"&gt;");

        soapMessage.append("&lt;ns1:in0&gt;").append(businessServiceName).append("&lt;/ns1:in0&gt;");

        soapMessage.append("&lt;ns1:in1&gt;").append(StringEscapeUtils.escapeXml(message.toString())).append(

                "&lt;/ns1:in1&gt;");

        soapMessage.append("&lt;ns1:in2&gt;").append("").append("&lt;/ns1:in2&gt;");

        soapMessage.append("&lt;/ns1:call&gt;");

        soapMessage.append("&lt;/soap:Body&gt;");

        soapMessage.append("&lt;/soap:Envelope&gt;");

        logger.debug("发送到asip的soap消息内容:" + soapMessage);

        byte\[] b = soapMessage.toString().getBytes();

        HttpURLConnection con = (HttpURLConnection) connection;

        con.setRequestProperty("Content-Length", String.valueOf(b.length));

        con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

        con.setRequestMethod("POST");

        con.setDoOutput(true);

        con.setDoInput(true);

        OutputStream out = con.getOutputStream();

        out.write(b);

        out.close();

        // 发送完毕

        // 读取响应

        InputStreamReader isr = new InputStreamReader(con.getInputStream());

        BufferedReader in = new BufferedReader(isr);

        String inputLine = null;

        StringBuffer result = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {

            result.append(inputLine);

        }

        in.close();

        logger.debug("接收到asip的soap消息内容:" + result);

        /\**

         * 解析soap消息

         \*/

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.parse(new InputSource(new StringReader(result.toString())));

        String callResponse = getAsipReturnString(doc);

 

        return ResponseMessage.newInstance(callResponse);

    }