http client 方式调用webservice

对于初学者而言,拼装soap请求报文似乎不是很简单的事情,但这里面有一个简单的方式获得soap报文,就是通过soapui插件,可以获得请求报文,具体了解soapui,这里不赘述,上代码

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 通过UrlConnection调用Webservice服务
*
*/
public class HttpClientTest {

    public static void main(String[] args) throws Exception {
        //服务的地址
        URL wsUrl = new URL("http://localhost:8080/server/plus?wsdl");
       
        HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
       
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
       
        OutputStream os = conn.getOutputStream();
       
       
        String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://server/\">"+
        "<soapenv:Header/>"+
        "<soapenv:Body>"+
        "<ser:add>"+
        "<arg0>5</arg0>"+
        "<arg1>6</arg1>"+
        "</ser:add>"+
        "</soapenv:Body>"+
        "</soapenv:Envelope>";
       
        os.write(soap.getBytes());
        InputStream is = conn.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);
       
        is.close();
        os.close();
        conn.disconnect();
    }
}

你可能感兴趣的:(http client 方式调用webservice)