通过UrlConnection调用Webservice服务

package com.ws;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class App {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        URL url = new URL("http://localhost:9999/hello");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        OutputStream outputStream = httpURLConnection.getOutputStream();
        String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://ws.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body><q0:sayHi><arg0>aaa</arg0></q0:sayHi></soapenv:Body></soapenv:Envelope>";
        outputStream.write(soap.getBytes());

        InputStream is = httpURLConnection.getInputStream();

        byte[] b = new byte[1024];
        int len = 0;
        String s = "";
        while ((len = is.read(b)) != -1) {
            String ss = new String(b, 0, len, "UTF-8");
            s += ss;
        }
        System.out.println(s);

        String xmlStr = s;
        StringReader sr = new StringReader(xmlStr);
        InputSource iss = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(iss);
        String str = doc.getElementsByTagName("return").item(0).getTextContent();

        is.close();
        outputStream.close();
        httpURLConnection.disconnect();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值