天天看點

http client 方式調用webservice

對于初學者而言,拼裝soap請求封包似乎不是很簡單的事情,但這裡面有一個簡單的方式獲得soap封包,就是通過soapui插件,可以獲得請求封包,具體了解soapui,這裡不贅述,上代碼

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

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();

}

}