通过UrlConnection调用Webservice服务
淩度奢望 ✦ 暂无邮箱
package com.wang.webservice.service;  

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class HelloService {

public String sayHello( String name ){
System.out.println(name);
return "hello " + name;
}

public static void main(String[] args) {
Endpoint.publish("http://127.0.0.1:1234/helloservice", new HelloService());
}

}

编写客户端代码: 

package com.wang.webservice.urlconnection;  

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
* 通过UrlConnection调用Webservice服务
*/
public class App {

public static void main(String[] args) {
URL wsUrl = null;
try {

wsUrl = new URL("http://127.0.0.1:1234/helloservice");
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:q0=\"http://service.webservice.wang.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<soapenv:Body><q0:sayHello><arg0>tom</arg0></q0:sayHello></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();

} catch (MalformedURLException e) {
System.out.println("创建URL失败");
e.printStackTrace();
} catch (IOException e) {
System.out.println("URL打开失败");
e.printStackTrace();
}

}

}


 

Submit
no comments yet~